请参阅下面的SQL代码:
declare @Classification as varchar(5)
set @Classification =''
declare @ClassificationSQL as nvarchar(4000)
set @ClassificationSQL=''
declare @cnt int
declare @counts int
DECLARE NicheDeletionOffenderCursor CURSOR FOR
select classification from dbnicheoffenderclassificationlookup
Open NicheDeletionOffenderCursor
FETCH NEXT FROM NicheDeletionOffenderCursor INTO @Classification
WHILE @@FETCH_STATUS = 0
BEGIN
If @ClassificationSQL=''
set @ClassificationSQL='classification like ' + char(39) + '%' + @Classification + '%' + char(39)
else
set @ClassificationSQL=@ClassificationSQL + ' OR classification like ' + char(39) + '%' + @Classification + '%' + char(39)
FETCH NEXT FROM NicheDeletionOffenderCursor INTO @Classification
END
CLOSE NicheDeletionOffenderCursor
DEALLOCATE NicheDeletionOffenderCursor
SET @ClassificationSQL = 'select count(*) as cnt from person where id=903 and (' + @ClassificationSQL + ')'
EXECUTE sp_executesql @ClassificationSQL, N'@cnt int OUTPUT', @cnt=@Counts OUTPUT
如何将@ClassificationSQL的计数输出分配给在TSQL的下一部分中使用的变量?
答案 0 :(得分:1)
这里有几件事需要提及:
@cnt
)内部声明使用的变量(即在顶部)SELECT @var = @var + column
构造将连接@Classification
)''
)进行转义。但是,可能只是优先使用CHAR(39)
,而有些人会发现它更具可读性。SELECT @var = expression FROM...
)最终结果:
DECLARE @ClassificationSQL NVARCHAR(4000)
DECLARE @Counts INT
SET @ClassificationSQL = COALESCE(@ClassificationSQL + N' OR ', '')
+ N'classification LIKE ''%'
+ classification
+ N'%'''
FROM dbnicheoffenderclassificationlookup
SET @ClassificationSQL =
N'SELECT @TempCount = COUNT(*) FROM person WHERE id = 903 AND ('
+ @ClassificationSQL
+ N')'
EXECUTE sp_executesql
@ClassificationSQL,
N'@TempCount INT OUTPUT',
@TempCount = @Counts OUTPUT
SELECT @Counts
答案 1 :(得分:0)
请参阅以下示例,了解如何获取动态查询的输出(在SQL Server 2008 R2中测试)。从中获取想法的实际帖子How to get sp_executesql result into a variable?
DECLARE @retval int;
DECLARE @SQL nvarchar(500);
DECLARE @Param nvarchar(500);
DECLARE @table nvarchar(50)
SELECT @table = N'newperson'
SELECT @SQL = N'SELECT @retvalOUT = MAX(salary) FROM ' + @table;
SET @Param = N'@retvalOUT int OUTPUT';
EXEC sp_executesql @SQL, @Param, @retvalOUT=@retval OUTPUT;
SELECT @retval;
您可以相应地更改您的程序。