我想将动态SQL的结果输出到一个名为@Count的变量中,但不确定语法甚至代码应该是什么样的。
代码如下:
declare @tab nvarchar(255) = 'Person.person'
declare @Count int
declare @SQL nvarchar(max) = 'select count(*) from '+ @tab
exec(@SQl)
select @Count
谢谢
答案 0 :(得分:3)
这是另一种方法,它也可以安全地解决SQL注入问题:
/* Counts the number of rows from any non-system Table, *SAFELY* */
-- The table name passed
DECLARE @PassedTableName as NVarchar(255) = 'Person.Person';
-- Make sure this isn't a SQL Injection attempt
DECLARE @ActualTableName AS NVarchar(255)
SELECT @ActualTableName = TABLE_SCHEMA + '.' + TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = PARSENAME(@PassedTableName,1)
AND TABLE_SCHEMA = PARSENAME(@PassedTableName,2)
-- make a temp table to hold the results
CREATE TABLE #tmp( cnt INT );
-- create the dynamic SQL
DECLARE @sql AS NVARCHAR(MAX)
SELECT @sql = 'SELECT COUNT(*) FROM ' + @ActualTableName + ';'
-- execute it and store the output into the temp table
INSERT INTO #tmp( cnt )
EXEC(@SQL);
-- Now, finally, we can get it into a local variable
DECLARE @result AS INT;
SELECT @result = cnt FROM #tmp;
答案 1 :(得分:1)
您可以利用sp_executesql
执行count()查询,并输出@Count。
试试这个:
-- Set the table to count from
declare @tab nvarchar(255) = 'Person.person'
-- Assign the SQL query
declare @SQL nvarchar(255) = N'SELECT count(*) FROM ' + @tab
-- Pepare for sp_executesql
declare @Count int
declare @Params nvarchar(100) = N'@Count int output'
-- Set the count to @Count
exec sp_executesql @SQL, @Params, @Count=@Count output
-- Output @Count
select @Count
最后一件事:Person.person看起来像是在尝试从Person表中引用person列。但上述查询是对您在问题中尝试实现的内容的字面表示。
答案 2 :(得分:1)
以下问题与您在此处提出的问题非常相似。
sp_executeSql with output parameter
DECLARE @retval int
DECLARE @sSQL nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);
DECLARE @tablename nvarchar(50)
SELECT @tablename = N'products'
SELECT @sSQL = N'SELECT @retvalOUT = MAX(ID) FROM ' + @tablename;
SET @ParmDefinition = N'@retvalOUT int OUTPUT';
EXEC sp_executesql @sSQL, @ParmDefinition, @retvalOUT=@retval OUTPUT;
SELECT @retval;