Tuesday, March 20, 2012

Passing a table name

I would like to pass the name of a table in my update query. It goes something like :
set @.Table = 'TableA'
UPDATE
@.Table
SET
Company_id = @.Company_id
However I get a syntax error when I try to pass the table name like this.Try this

Declare
@.Table nvarchar(25)
, @.sql nvarchar(500)
, @.Company_id nvarchar(15)

Set @.Table = 'TableA'
Set @.Company_id = 'MyCompany'

Set @.sql = 'Update ' + @.Table + ' Set Company_id = ''' + @.Company_id + ''''

Print @.sql
--Exec sp_executesql @.sql

This will show you what the statement would look like if you hard coded it.

Then uncomment out this line "Exec sp_executesql @.sql" and the statement will execute.

later,
mkal

No comments:

Post a Comment