I am trying to use a variable as part of a column name in a dynamic SQL statement.
I have 4 columns that are called Player1Action, Player2Action, Player3Action and Player4Action.
Depending on the varaible @CurrentPlayerId, I want to update the relevant player column with some data.
So for example, if CurrentPlayerId contains 1, then update column Player1Action.
I realise I could achieve this with a series of IF statements, but I would like to do it in a cleaner manner.
I have the following code, but I think my escaping is causing issues. I have re-written this a view times but I don't seem to be able to get it to work.
DECLARE
@CurrentPlayerId INT,
@CurrentPlayerBetAmount nvarchar(MAX),
@stmt nvarchar(MAX);
SET @CurrentPlayerId = 1
SET @CurrentPlayerBetAmount = 100
SET @stmt = N'UPDATE HandCurrent SET ''Player'' ''+'' @CurrentPlayerId ''+'' ''Action'' = 1 '','' ''Player'' ''+'' @CurrentPlayerId ''+'' ''ActionSize'' = @CurrentPlayerBetAmount'
EXECUTE sp_executesql @stmt
If I run this as a select I get the following returned.
UPDATE HandCurrent SET 'Player' '+' @CurrentPlayerId '+' 'Action' = 1 ',' 'Player' '+' @CurrentPlayerId '+' 'ActionSize' = @CurrentPlayerBetAmount
SELECT @stmtto see the result sql ?