Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SQL assigning variable fields variable values

Status
Not open for further replies.

WMitchellCPQ

Programmer
Sep 28, 2001
54
US
Hi there folkes :)

Ive run into a problem with my update statement. In it I wish to have a variable represting a FieldName and another representing the new value.

Here is my code however the update statement wont work as the variable field name takes the value of the value.

How do I fix this ... any help appreciated
Code:
UPDATE dbo.OrderItems
SET @tmpFieldName = @tmpFieldValue
WHERE OrderID = @OrderID

W
 
DECLARE @SQLCommand VarChar(200)

SET @SQLCommand =

'UPDATE dbo_OrderItems
SET ' + @tmpFieldName + ' = @tmpFieldValue
WHERE OrderID = @OrderID'

EXEC (@SQLCommand)

Thanks

J. Kusch
 
I think you'll need to create a dynamic sql String to hold your statement and values...then execute it like

set @str = 'UPDATE dbo_OrderItems
SET ' + @tmpFieldName +' = ' + @tmpFieldValue + '
WHERE OrderID = ' + @OrderID
 
I need to escape an apostrophe
e.g.

Code:
SET ' + @tmpFieldName +' =  "'+ @tmpFieldValue + '" WHERE OrderID = "' + @OrderID + '=9563'
 
so what is the error you're getting that is making this not work?
 
That code seems to work ok but as such as I change the value for the OrderId to a variable it gives me the following...

Code:
set @str = 'UPDATE dbo.OrderItems
SET'+ @tmpFieldName + '="'+ @tmpFieldValue +'"WHERE OrderID ="'+@OrderID +'"'


Server was unable to process request. ---> System.ArgumentException: Syntax error converting the varchar value 'UPDATE dbo_OrderItems
SET Model260RailOnly = "Jim " WHERE OrderID = "' to a column of data type int.



Thanks for looking at this :)
W
 
I don't think you need the doubl quotes around the @orderID
can you do a print of your statement results?

dlc
 
Here u go...

set quoted_identifier off

drop table test
create table test(a varchar(15))
insert into test values (1)
insert into test values (2)
insert into test values ('3abc')

declare @sql varchar(50), @tmpFieldName varchar(10), @tmpFieldValue varchar(10),
@OrderID varchar(10)

set @OrderID = '3abc'
set @tmpFieldName = 'a'
set @tmpFieldValue = 'bcd'

select @sql = 'UPDATE Test set ' + @tmpFieldName + ' = ''' + @tmpFieldValue
+ ''' WHERE a = ''' + @OrderID + ''''

print @sql
--OUTPUT will be >> UPDATE Test set a = 'bcd' WHERE a = '3abc'
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top