将变量动态地设置为其自身值的值-可能吗?

时间:2019-01-29 14:10:36

标签: sql sql-server tsql stored-procedures

使用TSQL

尝试设置@DynamicValue = 23,这是下面的“等于”参数,但无法弄清楚。

DECLARE @DynamicValue VARCHAR(MAX) = '@PersonID';
DECLARE @PersonID INT = 23;
DECLARE @PlaceID INT = 48;
DECLARE @ThingID INT = 29;
DECLARE @nSQL NVARCHAR(MAX);

SET @nSQL = N'SELECT @Parameter2 = ' + CAST(@DynamicValue AS VARCHAR(MAX));
-- This is where the error is. If I used @PersonID here it would be fine but I want this to be dynamic

EXEC sp_executesql @nSQL,
                   N'@Parameter2 NVARCHAR(MAX) OUTPUT',
                   @Parameter2 = @DynamicValue OUTPUT;

SELECT @DynamicValue;

有什么想法吗?不同的方法?

4 个答案:

答案 0 :(得分:1)

我唯一看到的方式:

DECLARE @DynamicValue VARCHAR(MAX) = '@PersonID';
DECLARE @PersonID INT = 23;
DECLARE @PlaceID INT = 48;
DECLARE @ThingID INT = 29;

SELECT @DynamicValue = CAST(CASE @DynamicValue 
    WHEN '@PersonID' THEN @PersonID
    WHEN '@PlaceID' THEN @PlaceID
    WHEN '@ThingID' THEN @ThingID END as VARCHAR(MAX))
SELECT @DynamicValue

答案 1 :(得分:0)

EzLo在上面的评论中说,无法访问在动态SQL外部声明的变量,这使我以以下方式重写代码,似乎可以正常工作:

SET @nSQL = N'DECLARE @PersonID INT = ' + CAST(@PersonID as varchar)
         +' DECLARE @PlaceID INT = ' + CAST(@PlaceID as varchar)
         +' DECLARE @ThingID INT ='  + CAST(@ThingID as varchar)
         +' SELECT @Parameter2 = ' + CAST(@DynamicValue AS VARCHAR(MAX));

答案 2 :(得分:0)

您只需要将所有参数传递到执行分配的动态批处理中即可。

赞:

DECLARE @DynamicValue VARCHAR(MAX) = '@PersonID';

DECLARE @PersonID INT = 23;
DECLARE @PlaceID INT = 48;
DECLARE @ThingID INT = 29;
DECLARE @nSQL NVARCHAR(MAX);

SET @nSQL = N'set @Parameter2 = ' + CAST(@DynamicValue AS VARCHAR(MAX));

EXEC sp_executesql @nSQL,
                   N'@PersonID int, @PlaceID int, @ThingID int, @Parameter2 NVARCHAR(MAX) OUTPUT',
                   @PersonID = @PersonID, @PlaceID = @PlaceID, @ThingID = @ThingID, @Parameter2  = @DynamicValue OUTPUT;

SELECT @DynamicValue;

答案 3 :(得分:0)

还有另一种方法可以完成相同的操作,但是您仍然必须列出所有参数:

DECLARE @DynamicValue VARCHAR(MAX) = '@PersonID';
DECLARE @PersonID INT = 23;
DECLARE @PlaceID INT = 48;
DECLARE @ThingID INT = 29;

DECLARE @DynamicValues TABLE (Parameter VARCHAR(MAX), Value INT)
INSERT INTO @DynamicValues VALUES 
('@PersonID',@PersonID),
('@PlaceID',@PlaceID),
('@ThingID',@ThingID);

SELECT @DynamicValue = CAST(Value as VARCHAR(MAX))
FROM @DynamicValues WHERE Parameter = @DynamicValue
SELECT @DynamicValue