April 17, 2010 at 1:25 am
Hi all
I have a scenerio where i have to select a column dynamically to update..
its some thing like this
update dbo.tbl_data set var2= @toUpdate
where var1 =@selecteditem
here var1 and var2 are column names which i want to be dynamic...
thank in advance for your reply....
April 17, 2010 at 1:38 am
You can use Dynamic SQL for the same
DECLARE@strSQLVARCHAR(500)
DECLARE@toUpdateVARCHAR(100)
DECLARE@selecteditemVARCHAR(100)
SELECT@toUpdate = 'var2_N',
@selecteditem = 'var1_N'
SELECT@strSQL = ' UPDATE dbo.tbl_data '
+ ' SET var2 = ' + @toUpdate
+ ' WHERE var1 = ' + @selecteditem
EXECUTE ( @strSQL )
How to post data/code on a forum to get the best help - Jeff Moden
http://www.sqlservercentral.com/articles/Best+Practices/61537/
April 17, 2010 at 2:05 am
actually i have to pass the column name as a parameter
i have a table with various column names and i want to give control
to user to select the columns to update.
the user will select two columns dynamically,something like this
(@ColumnSelected nvarchar(max),
@ColumnToUpdate nvarchar(max),
as
begin
update tbl_data
set @ColumnToUpdate = xxx
where @ColumnSelected = yyy
April 17, 2010 at 4:32 am
You can use like this
Even You can pass the value xxx and yyy as a parameter
to make it more generalize.
DECLARE @SQL AS VARCHAR(MAX)
DECLARE @ColumnToUpdate nvarchar(max)
DECLARE@ColumnSelected nvarchar(max)
SELECT@ColumnToUpdate = 'Var1',
@ColumnSelected = 'Var2'
SET@SQL= ' Update tbl_data'
+' SET ' + @ColumnToUpdate + ' = xxx'
+' WHERE ' + @ColumnSelected + '= yyy'
EXECUTE ( @SQL )
Vaibhav K Tiwari
To walk fast walk alone
To walk far walk together
April 17, 2010 at 4:42 am
basically my recommendation mirrors vaibhav's below; four parameters, two for column names and two for values;
if you are going to do that, however, why not just build the whole , complete update statement on the client app(which already has determined the table and column names, along with the new values)
it's probably easier and cleaner to build the whole string and just .ExecuteNonQuery instead of an adapter with a parameter object and four parameters; also makes it easier in situations where you are changing TWO columns at the same time;
Lowell
April 18, 2010 at 8:28 pm
My recommendation would be to redesign the table to use a more relational form.
http://databases.about.com/od/specificproducts/a/firstnormalform.htm
April 18, 2010 at 9:50 pm
I agree with Paul on this...
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 7 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply