Monday, March 19, 2012

Dynamically select column

Hey all. I'm trying to create a stored proc that will update a variable column, depending on the parameter I pass it. Here's the stored proc:


CREATE PROCEDURE VoteStoredProc
(
@.PlayerID int,
@.VoteID int,
@.BootNumber nvarchar(50)
)
AS

DECLARE @.SQLStatement varchar(255)
SET @.SQLStatement = 'UPDATE myTable SET '+ @.BootNumber+'='+ @.VoteID + ' WHERE (PlayerID = '+ @.PlayerID +')'

EXEC(@.SQLStatement)

GO

I get the following error:


Syntax error converting the nvarchar value 'UPDATE myTable SET Boot3=' to a column of data type int

The update statement is good, because if I use the stored proc below (hard-coded the column), it works fine.


CREATE PROCEDURE VoteStoredProc
(
@.PlayerID int,
@.VoteID int,
@.BootNumber nvarchar(50)
)
AS

UPDATE
myTable
SET
Boot3 = @.VoteID
WHERE
PlayerID = @.PlayerID
GO

Is there a way to dynamically choose a column/field to select from? Or is my syntax incorrect..?
Thanks!Try this:


CREATE PROCEDURE VoteStoredProc

(

@.PlayerID int,
@.VoteID int,
@.BootNumber varchar(50)

)

AS

DECLARE @.SQLStatement varchar(255)

SET @.SQLStatement = 'UPDATE myTable SET '+ @.BootNumber+ ' = ' + CAST(@.VoteID as VARCHAR(10)) + ' WHERE (PlayerID = '+ CAST(@.PlayerID as VARCHAR(10)) +')'

EXEC(@.SQLStatement)
GO

Casting the integers to varchars so they can be concatenated into the larger string.

Hope this helps,
John|||John:

Brilliant! Thanks; works beautifully.

JP

No comments:

Post a Comment