【问题标题】:Must declare scalar variable in SQL Server stored procedure必须在 SQL Server 存储过程中声明标量变量
【发布时间】:2012-08-11 07:42:54
【问题描述】:

我有一个存储过程,它检索多行 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);
}

【问题讨论】:

  • 您为什么要为此使用动态 SQL? NotifyOn 的数据类型是什么?
  • NotifyOn 数据类型为日期时间

标签: sql-server stored-procedures


【解决方案1】:

为什么要使用动态 SQL?

就这样做

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

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

【讨论】:

  • 没有一张桌子我有“VendorTickets”...对不起,这是一个错误
  • i 只有一个表第一个查询进行选择操作,第二个根据第一个选择查询中的返回值进行更新
  • 在您的示例中,我认为您正在尝试设置值并返回数据的第一个查询。你不能两者都做
  • 如何检查 Notify on 是否大于 1900-01-01?
  • 通知在哪里>'1900-01-01'。如果你想要一个空日期,为什么不让它为空?
【解决方案2】:
Select @Ticket=Ticket,VendorTicket[Vendor Ticket],Comments From dbo.VendorTickets Where NotifyOn <= GetDate() And IsNull(NotifyOn,0)<>0

意味着你选择的结果将被写入变量@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
      )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 2016-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多