必须在SQL Server存储过程中声明标量变量

时间:2012-08-11 07:42:55

标签: sql-server stored-procedures

我有一个存储过程,它检索多行的3列项。我正在以DataTable的格式检索。当我调试它时,它给了我错误

  

必须声明标量变量@Ticket。

但我已经宣布过了。

存储过程:

BEGIN

Declare @Ticket Numeric(28,0)
Declare @SQL VarChar(Max)
Declare @SQLUpdate VarChar(Max)

 Set @SQL='Select @Ticket=Ticket,VendorTicket[Vendor Ticket],Comments From dbo.VendorTickets Where NotifyOn <= GetDate() And IsNull(NotifyOn,0)<>0 '
 Exec(@SQL)

 Set @SQLUpdate='Update dbo.VendorTicket Set NotifyOn=0 Where Ticket=@Ticket'
 Exec(@SQLUpdate)

END

调用存储过程的代码

SqlConnection oConn = null;
DataTable dtReturn = null;
try
{
getConnection(ref oConn, 1);
using (SqlStoredProcedure sspObj = new SqlStoredProcedure("dbo.usp_checkNotification", oConn, CommandType.StoredProcedure))
{
dtReturn = sspObj.ExecuteDataTable();
sspObj.Dispose();
}
closeConnection(ref oConn);
}

2 个答案:

答案 0 :(得分:0)

为什么使用动态SQL?

就这样做

 Update dbo.VendorTickets
 Set NotifyOn=0 
 Where NotifyOn <= GetDate() 
 And NotifyOn IS NOT NULL

请注意,将日期时间(NotifyOn)设置为0会将其设置为1900-01-01。

答案 1 :(得分:0)

Select @Ticket=Ticket,VendorTicket[Vendor Ticket],Comments From dbo.VendorTickets Where NotifyOn <= GetDate() And IsNull(NotifyOn,0)<>0

表示您的select的结果将写入变量@Ticket,因此@Ticket必须是表变量,但您声明@Ticket Numeric(28,0)。 你可以通过下一个sql脚本做你想做的事情:

Update dbo.VendorTicket 
Set NotifyOn=0 
Where Ticket in (
      Select Ticket 
      from dbo.VendorTickets 
      Where NotifyOn <= GetDate() And IsNull(NotifyOn,0)<>0
      )
相关问题