SQL Server Setting a variable using a query that includes a different variable

icomxhvb  于 2023-11-16  发布在  其他
关注(0)|答案(1)|浏览(96)

I am working with a routine that manages several databases. Each DB has an activity log. I want to loop through the activity logs and get the latest activity date (formatted yyyy-MM-dd hh:mm ) for each DB.

If I hard code the database/table name into this statement, it works just fine.

SET @LatestLogDT = (SELECT FORMAT(MAX([ActivityDT]), N'yyyy-MM-dd hh:mm') FROM MyDB.dbo.MyTable);

However, if I put this in a loop and try to insert the db/table name as a dynamic variable, it fails, saying I must declare the variable. I've whittled the code down as thin as possible to demonstrate the issue. In this example, I declare @DBTableName as the db/table name, and I'm manually assigning here to show the problem without having to include the looping code, which is just a distraction.

DECLARE @DBTableName VARCHAR(50) = '[MyDB].[dbo].[MyTable]';
DECLARE @LatestLogDT VARCHAR(25);

SET @LatestLogDT = (SELECT FORMAT(MAX([ActivityDT]), N'yyyy-MM-dd hh:mm') FROM @DBTableName);
SELECT @LatestLogDT

However, when I run this code, I get this error message:

Must declare the table variable "@DBNAME".

Next, I tried creating an SQL string and executing that string, but I get the same error.

I feel like I've seen this done before, but clearly I'm missing something. Probably sometime quite simple. Hoping one of you geniuses can put me on the right track.

bejyjqdl

bejyjqdl1#

Please try with a dynamic Transact-SQL statement:

DECLARE @DBTableName VARCHAR(50) = '[MyDB].[dbo].[MyTable]';
DECLARE @LatestLogDT NVARCHAR(MAX);

SET @LatestLogDT = N'SELECT FORMAT(MAX([ActivityDT]), ''yyyy-MM-dd hh:mm'') FROM' + @DBTableName;
EXEC sp_executesql @LatestLogDT

More info and examples on sp_executesql

相关问题