如何在sql语句中将数据库声明为变量

时间:2019-04-13 09:52:34

标签: sql-server tsql

我在将sql语句(MS SQL)数据库声明为变量时遇到问题,我有此过程, 任何人都可以帮助谢谢:)

DECLARE @ID int = 700001158
DECLARE @STRING VARCHAR(250) = 'StringResource_EN'

SELECT string.[value],item.[id] FROM ItemResource item LEFT JOIN **@STRING** string ON item.[name_id] = string.[code]
WHERE item.[id] = @ID

我得到了错误:

  

[42000] [Microsoft] [SQL Server Native Client 11.0] [SQL Server]必须声明表变量“ @STRING”。 (1087)   引用

这应该是这个结果:

  

id = 700001158   值=恶魔净化:盾牌

编辑: 我尝试过

DECLARE @ID int = 700001158
DECLARE @STRING VARCHAR(250) = 'StringResource_EN'
DECLARE @sql NVARCHAR(1000)

SET @sql =  'SELECT string.[value],item.[id] FROM ItemResource item LEFT JOIN '+@STRING+' string ON item.[name_id] = string.[code]
WHERE item.[id] = @ID'

EXEC sp_executesql @sql;

我也知道了

  

[42000] [Microsoft] [SQL Server Native Client 11.0] [SQL Server]必须声明标量变量“ @ID”。 (137)

1 个答案:

答案 0 :(得分:2)

您将需要为此使用动态SQL:

ALTER PROCEDURE [dbo].[cpanel_get_warehouse_item]
@IN_ACCOUNT_ID      INT,
@IN_STRING_DB VARCHAR(255),
@ITEM_COUNT         INT OUTPUT,
@GOLD           INT OUTPUT

AS
SET NOCOUNT ON
SET @ITEM_COUNT = (SELECT COUNT(*) FROM [Telecaster].dbo.[Item] WHERE [account_id] = @IN_ACCOUNT_ID AND [code] > 0)
SET @GOLD = (SELECT [cnt] FROM [Telecaster].dbo.[Item] WHERE [account_id] = @IN_ACCOUNT_ID AND [code] = 0 AND [gcode] = 126)

DECLARE @sql NVARCHAR(1000);

SELECT @sql =  'SELECT string.[value] as name,item.[code] as id ,item.[cnt],item.[level],item.[enhance],data.[icon_file_name] as icon
FROM [Telecaster].dbo.[Item] item LEFT JOIN [Arcadia].dbo.[ItemResource] data on data.[id] = item.[code]
LEFT JOIN [Arcadia].dbo.' + @IN_STRING_DB +  'string on data.[name_id] = string.[code]
WHERE item.[account_id] = ' + @IN_ACCOUNT_ID' + AND item.[code] > 0 ORDER BY item.[sid] asc'

EXEC sp_executesql @sql;

正如米尔尼正确指出的那样,每当您使用动态SQL时,您都应该注意SQL注入。