请参阅以下代码:
declare @Classification as varchar(5)
set @Classification =''
declare @ClassificationSQL as nvarchar(4000)
declare @PersonSQL as nvarchar(4000)
set @ClassificationSQL=''
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 @cnt=count(*) from tbl_goccivgperson where lid=@LID and (' + @ClassificationSQL + ')'
SET @PersonSQL = 'SELECT * FROM tbl_goccivgperson WHERE LID=@LID and (' + @ClassificationSQL + ')'
DECLARE @CoreSystemIndexValue varchar(100)
SET @CoreSystemIndexValue=''
DECLARE NicheDeletionCursor CURSOR FOR
SELECT TOP 1 coresystemindexvalue from dbdisposals where datasetname='NICHECI'
Open NicheDeletionCursor
FETCH NEXT FROM NicheDeletionCursor INTO @CoreSystemIndexValue
WHILE @@FETCH_STATUS = 0
BEGIN
EXECUTE sp_executesql @ClassificationSQL, N'@LID decimal(25,0),@cnt int OUTPUT', @LID=@CoreSystemIndexValue, @cnt=@Counts OUTPUT 'Line 38
--If @Counts > 0
--begin
--Check that all the nominals in Niche are ready for deletion
EXECUTE sp_executesql @PersonSQL, N'@LID decimal(25,0)', @LID=@CoreSystemIndexValue 'Line 42
--end
--Else
--Check that all Persons (all are RCWs) in CIS and Niche are ready for deletion
FETCH NEXT FROM NicheDeletionCursor INTO @CoreSystemIndexValue
END
CLOSE NicheDeletionCursor
DEALLOCATE NicheDeletionCursor
我得到的错误是:必须声明标量变量“@cnt”。注释掉第38行或第2行42解决了这个问题。问题似乎是第42行。在@PersonSQL中没有提到:@cnt所以我不明白为什么我会遇到这个问题。
答案 0 :(得分:2)
您有此代码
SET @ClassificationSQL = 'select @cnt=count(*) from tbl_goccivgperson where lid=@LID and (' + @ClassificationSQL + ')'
SET @PersonSQL = 'SELECT * FROM tbl_goccivgperson WHERE LID=@LID and (' + @ClassificationSQL + ')'
它使用@ClassificationSQL
计算中的@PersonSQL
变量,因此@cnt
也会在那里结束。我想你想要做的事实上是
SET @PersonSQL = 'SELECT * FROM tbl_goccivgperson WHERE LID=@LID and (' + @ClassificationSQL + ')'
SET @ClassificationSQL = 'select @cnt=count(*) from tbl_goccivgperson where lid=@LID and (' + @ClassificationSQL + ')'
或者更好的是,不要重复使用@ClassificationSQL
变量
declare @ClassificationSQL as nvarchar(4000)
declare @PersonSQL as nvarchar(4000)
declare @ConditionSQL as nvarchar(4000) --or a name that makes sense
-- calculate @ConditionSQL
SET @ClassificationSQL = 'select @cnt=count(*) from tbl_goccivgperson where lid=@LID and (' + @ConditionSQL + ')'
SET @PersonSQL = 'SELECT * FROM tbl_goccivgperson WHERE LID=@LID and (' + @ConditionSQL + ')'