February 20, 2006 at 10:07 am
I'm trying to update a column in multiple tables all with a common column name. My statement looks as follows:
Declare @Table varchar(30)
declare csrTable Cursor for
SELECT sysobjects.name
FROM syscolumns INNER JOIN
sysobjects ON syscolumns.id = sysobjects.id
WHERE (syscolumns.name = 'branch') AND (sysobjects.type = 'U')
open csrTable
while (1=1)
begin
fetch next from csrTable into @Table
if (@@fetch_Status <> 0)
Break
Else
UPDATE @Table
SET branch = 3
WHERE (branch = 940)
End
close csrTable
deallocate csrTable
When I go to parse the query, I get the following error:
Server: Msg 170, Level 15, State 1, Procedure sp_Mod_Branch, Line 18
Line 18: Incorrect syntax near '@Table'.
Can I use a variable for the table name? If so, what is its delcaration type?
In advance, I appreciate all of your assistance.
February 20, 2006 at 10:16 am
>>Can I use a variable for the table name? If so, what is its delcaration type?
No, you need to build SQL in a string and execute it dynamically. Search the forums on keywords "dynamic SQL".
February 20, 2006 at 10:59 am
The most obvious solution is building the dynamic SQL piece by piece:
declare @cmd varchar(8000)
set @cmd=''
select @cmd=@cmd + 'UPDATE ' + quotename(table_schema) + '.' + quotename(table_name)
+ ' SET ' + quotename(column_name) + ' = 3 WHERE ' + quotename(column_name) + ' = 940); '
from information_schema.columns
where column_name = 'MarketID'
exec (@cmd)
I prefer using replaceable tags to make it more readable (IMHO):
declare @cmd varchar(8000)
set @cmd=''
select @cmd=@cmd + replace(replace(replace(replace(replace(
'UPDATE <schema>.<table> SET <col> = <newvalue> WHERE <col> = <oldvalue> '
,'<schema>',quotename(table_schema))
,'<table>',quotename(table_name))
,'<col>',quotename(column_name))
,'<oldvalue>',940)
,'<newvalue>',3)
from information_schema.columns
where column_name = 'MarketID'
exec (@cmd)
February 20, 2006 at 1:22 pm
just build your update statement string dynamically and execute the string using exec or sp_executesql...
-Krishnan
February 20, 2006 at 1:28 pm
Thanks All! I got the gist of it. I appreciate all of your input and expertise.
Thanks again!!!
February 21, 2006 at 7:29 pm
Scott...
What editor are you using? Thanks...
--Jeff Moden
Change is inevitable... Change for the better is not.
February 22, 2006 at 7:59 am
I copied the code from SQL 2005 Management Studio. You have to fix all the double-spaced lines, restore the indenting, change the font back to a non-proportional font, etc. But I like keeping the color-coding.
Viewing 7 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply