Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
mdhingra01
Posting Yak Master
179 Posts |
Posted - 2005-08-18 : 09:23:04
|
| Hi, Is there a better way of doing this??? I have to run an update statement in my script that actually updates or 30 columns. I am hoping I do not have to hard code the thirty columns.Here is an example of what I have. I really want to know if you can do the @setSTring variable in the Update statement. If so how do you execute the SQL statement. Your help is greatly appreciated...If you have a better suggestion, I would love to know about it.DECLARE getColumns_cursor CURSOR FORSelect syscolumns.name from syscolumnsinner join sysobjects on syscolumns.id = sysobjects.id where sysobjects.Name = 'Table1'OPEN getColumns_cursorDECLARE @setString varchar(600)DECLARE @getColumnName varchar(50)SET @setString = 'Set '-- Perform the first fetch.FETCH NEXT FROM getColumns_cursor INTO @getColumnName-- Check @@FETCH_STATUS to see if there are any more rows to fetch.WHILE @@FETCH_STATUS = 0BEGIN -- This is executed as long as the previous fetch succeeds. set @setString = @setString + 'BOCC.' + @getColumnName + ' = ' + 'NOCC.' + @getColumnName + ', ' --print @setString FETCH NEXT FROM getColumns_cursor INTO @getColumnNameEND--print @setStringCLOSE getColumns_cursorDEALLOCATE getColumns_cursorGOUPDATE table1 @setSTringWHERE RECORD_STATUS <> 'D' AND dbo.table1.ID NOT IN (SELECT ID FROM nocc.dbo.table1) |
|
|
SQLTEAMSteve
Starting Member
8 Posts |
Posted - 2005-08-18 : 13:32:08
|
| Use Openquery, that's how! You may need to phase-out your approach, and if you can, drop that cursor and opt for a While-Loop instead.The openquery syntax would look like this:declare @sSQL nvarchar(2500)declare @setString varchar(10)set @setString='new_value'set @sSQL=('update table1 set column1=''' + @setString + ''' where record_status not in (''D'') and ID not in(select id from nocc.dbo.table1 with(nolock))')print @ssqlexec sp_executeSQL @sSQLGo ahead and run the code up to the 'print @sSQL', it will work._________________________Stephen R Montgomery |
 |
|
|
tkizer
Almighty SQL Goddess
38200 Posts |
|
|
|
|
|