必须声明标量变量 - 存储过程

时间:2014-11-11 18:47:24

标签: sql-server stored-procedures

我不断收到错误消息:

[SqlException (0x80131904): Must declare the scalar variable "@DeviceSearch".]

即使将值传递到存储过程。这是SQL Trace:

exec InventorySearch @FieldName=N'Value',@TableName=N'AssetTag',@SearchTerm=N'00002730',@DeviceSearch=1

以下是存储过程中的变量声明以及使用它的行:

@DeviceSearch nvarchar(50),
@FieldName AS nvarchar(50),
@TableName AS nvarchar(50),
@SearchTerm nvarchar(50)

WHERE (@DeviceSearch = 1 and LogicallyDeleted = 0 and '+ @TableName+ '.'+ @FieldName+ 
                                                            ' like ''%@SearchTerm%'')

任何人都可以看到我需要做些什么来纠正这个问题吗?

2 个答案:

答案 0 :(得分:0)

尝试这个我相信它会有所帮助

   exec
InventorySearch 
@FieldName=N'Value',
@TableName=N'AssetTag',
@SearchTerm=N'00002730',
@DeviceSearch='1'

以及

WHERE (@DeviceSearch = '1' and LogicallyDeleted = 0
       and '+ @TableName+ '.'+ @FieldName+ 
      ' like ''%@SearchTerm%'')

答案 1 :(得分:0)

您可以在执行查询

时使用 print statements 的输出调试查询
ALTER PROCEDURE [dbo].[InventorySearch] 
    @FieldName AS nvarchar(50),
    @TableName AS nvarchar(50), 
    @SearchTerm nvarchar(50),
    @DeviceSearch bit
AS 
BEGIN
 DECLARE @SQL NVARCHAR(MAX)=

'SELECT AssetTag.Value, Device.LK_User, Device.LK_Location,
        AssetTag.CreatedOn, Device.AssetTypeId, AssetTag.StatusTypeId, 
        Device.DeviceID, Device.SerialNumber, Device.LogicallyDeleted
 FROM Device INNER JOIN AssetTag ON Device.DeviceID = AssetTag.DeviceID  
 WHERE '+CAST(@DeviceSearch as nvarchar(5))+'=1 and LogicallyDeleted = 0 and '+ (@TableName)+ '.'+ 
          (@FieldName) 
        +' like ''%' + (@SearchTerm ) +'%'''

print (@SQL)
EXEC (@SQL)
END