存储过程中的变量tablename和fieldname

时间:2014-11-11 13:03:47

标签: sql sql-server stored-procedures

当我尝试保存以下存储过程时,出现错误:

Msg 102,Level 15,State 1,Procedure InventorySearch,29行 '@FieldName'附近的语法不正确。

如何传入@TableName@FieldName并使用它们来定义应该使用哪个表和字段来搜索数据库?

ALTER PROCEDURE [dbo].[InventorySearch] 
    @FieldName AS nvarchar(50),
    @TableName AS nvarchar(50), 
    @SearchTerm nvarchar(50),
    @DeviceSearch bit
AS 
BEGIN
    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 @TableName.@FieldName like @SearchTerm
END

2 个答案:

答案 0 :(得分:1)

您需要创建Dynamic SQL,如下所示:

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 '+ (@TableName)+ '.'+ 
          (@FieldName) 
        +' like ''%' + (@SearchTerm ) +'%'''

print (@SQL)
EXEC (@SQL)
END

答案 1 :(得分:0)

您可以使用如下的动态查询编写代码。

ALTER PROCEDURE [dbo].[InventorySearch] 
    @FieldName AS nvarchar(50),
    @TableName AS nvarchar(50), 
    @SearchTerm nvarchar(50),
    @DeviceSearch bit
AS 
BEGIN
  DECLARE @Sql VARCHAR(MAX)=''
   SET @sql = '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 '+@TableName+'.'+@FieldName+' like '+@SearchTerm+''

  EXEC (@sql)
END