-1

I think I am trying to do something that is relatively straight forward, but keep getting the 'Must Declare Scalar Variable Error'. I have two variables:

DECLARE @CountOfThisCampaignSegment int
DECLARE @CountOfLastCampaignSegment int 

select @CountOfThisCampaignSegment = COUNT(seg1) from #thisCampaignFinal

select @CountOfLastCampaignSegment = COUNT(seg1) from #lastCampaignFinal

I read that somewhere else that it seems I need to turn them into nvarchar, but I need to compare these two variables for an IF statement down the track in my procedure - so I am not sure if that would cause problems?

If anyone could give me some advice and background on why SQL Server throws this error, it would be greatly appreciated!

Many Thanks!

4

1 回答 1

3

I suspect you actually have more than one batch in your script. Batches are separated by GO statements (by default) in SQL Server Management Studio.

Variables do not persist across batches. So this, for example, gives an error:

DECLARE @CountOfThisCampaignSegment int
DECLARE @CountOfLastCampaignSegment int 
select @CountOfThisCampaignSegment = COUNT(seg1) from #thisCampaignFinal
select @CountOfLastCampaignSegment = COUNT(seg1) from #lastCampaignFinal

-- other statements

GO

-- this line fails with "must declare scalar variable":
select @CountOfThisCampaignSegment, @CountOfLastCampaignSegment
于 2013-06-04T23:14:21.313 回答