Click here to Skip to main content
16,018,818 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I AM CREATING A PROCEDURE THAT WOULD UPDATE A DYNAMICALLY SELECTED COLUMN IN A SINGLE ROW; AND THERE IS STRONG REASON FOR THIS NEEED.

I AM A NEWBIE AND WOULD APPRICIATE EXPLICIT HELP

THE POSER:
How do I assign the value @InpArgXEl to the column, indicated by the variable @ColumnID, of PatternDtab (the database table) which primary key column is PattnRowID?
SQL
ALTER PROCEDURE dbo.TransPayPattn	
(
 @InpArgXEl XML OUTPUT,
 @ColumnID NCHAR(10),
 @RowNo INT OUTPUT
)

SET @ColumnID = '['+@Column+']'

--Litrarilly
UPDATE PatternDtab SET @ColumnID = @InpArgXEl WHERE PattnRowID=@RowNo

--what is the RIGHT way to do this?
DECLARE @Cmd  VARCHAR(MAX)

SET @Cmd= N'UPDATE PatternDtab SET '+@ColumnID+' = @InpArgXEl WHERE PattnRowID=@RowNo'

EXECUTE sp_executesql @Cmd

-- Confirmation
SET @InpArgXEl = (SELECT ... -- I ALSO NEED TO RE-EVALUATE THE CURRENT VALUE OF @ColumnID
Posted
Updated 7-Sep-11 2:35am
v3

Here's a small example of using the sp_executesql. At least one problem in your procedure is that you don't define the parameters at all:
SQL
CREATE TABLE DynTest (
  col1 varchar(100),
  col2 int
);

INSERT INTO DynTest VALUES ('A', 1);

CREATE PROCEDURE DynTestProc (@colName varchar(100), @value int) AS
DECLARE @sql        nvarchar(2000);
DECLARE @parameters nvarchar(2000);
BEGIN
  set @sql = N'UPDATE DynTest SET ' + @colName + ' = ''B'' WHERE col2 = @valueinsql';
  set @parameters = N'@valueinsql int';

  print @sql;
  print @parameters;

  exec sp_executesql @sql, @parameters, @valueinsql = @value;
END;

EXEC DynTestProc 'col1',1

SELECT * FROM DynTest

EXEC DynTestProc 'nonexistentcol',1 <-- error
 
Share this answer
 
OK, I'VE GOT IT.
THANKS TO U Mika Wendelius AND TO U TOO md_refay!
 
Share this answer
 
i 'll write upata statment only

declare @sql nvarchar(max)
select @sql='update DynTest Set '+@ColName +' = '''+@InpArgXEl+ ''' where PattnRowID ='+convert(nvarchar(5),@RowNo)

the secret is u must pass string value between ''
hope it be helpfull
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900