在SQL中声明变量

时间:2017-03-01 21:19:36

标签: sql sql-server

希望有人可以提供帮助。我仍然是SQL /编程的新手,所以这可能是一个容易回答的问题。

对于下面的脚本,我收到一个错误,它抱怨没有声明3个变量@startdate,@ enddate和@ result1rowcount。我知道我可以将这些声明进一步向下移动,它会起作用。但我想理解为什么它不能如下所述的理论,因为我已经在开始时声明了变量。这些声明必须在某些时候丢失。我不知道什么时候?如果有人可以解释为什么它会返回错误,那就太好了。我不想要如何重新编写它的建议。

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

Declare @count int
Declare @r int
Declare @start datetime
Declare @end datetime
Declare @startdate datetime
Declare @enddate datetime
Declare @Result1RowCount int

Set @start = DATEADD(d,0,DATEDIFF(d,0,getdate()-1))
set @end = DATEADD(d,0,DATEDIFF(d,0,getdate()))

Create table #tempwill
(feed int,
returnid int,
ProcessStartTime datetime,
ProcessEndTime datetime,
importcount int,
Selectedstartdate datetime,
Selectedenddate datetime)

Insert into #tempwill
Select feed, returnid, processstarttime, processendtime, importcount, selectedstartdate, selectedenddate
from Will_Database.dbo.Import
where selectedstartdate = @start 
and selectedenddate = @end

SET @COUNT = (select count(*) from #tempwill where importcount ='0')

IF @Count > 0 
     Begin
           exec @r = Bill_Database.dbo.op_Mail_2005 @profile_name = 'Testserver',
               @MailTo = 'joebloggs@hotmail.com',
               @MailBCC = '',
               @importance = 'HIGH',
               @subject = 'Warning - Numbers are not as expected',
               @body = 'Please investigate as todays numbers are not what we expected '

      End


GO

**Set @startdate = DATEADD(d,0,DATEDIFF(d,0,getdate()-2))
set @enddate = DATEADD(d,0,DATEDIFF(d,0,getdate()-1))**

CREATE TABLE #Results1 (ID int, Ref int, Code int, Explanation varchar(200), Timeof datetime)

INSERT #Results1 (ID, Ref, Code, Explanation, Timeof)
SELECT A.ID, B.Ref, A.Code, A.Explanation, A.Timeof
FROM Testserver.Will_database.dbo.codetime A
INNER JOIN Testserver.Bill_database.dbo.Coderegister B ON A.Code= B.Code AND A.Ref = B.Ref
WHERE  A.Timeof >= @StartDate
AND A.Timeof < @EndDate

**SELECT @Result1RowCount = @@RowCount**

**insert into Daily_Check values
( 1, 1, @Result1RowCount, @startdate, @enddate)**

1 个答案:

答案 0 :(得分:4)

问题在于你之前的GO声明。

这将它分成不同的批次,并且声明的变量超出了它们声明的批次之外的范围。

要解决此问题,只需删除GO