Execute SQL on Multiple Tables/Columns - New Feature in SQL Server 2000
In this latest article, Raghavendra introduces us to a feature available to us in SQL Server, allowing us to execute SQL statements on multiple tables and columns.
--Check whether to include TEXT, NTEXT, IMAGE data types SET @INCLUDE_NTI = UPPER(LTRIM(RTRIM(@INCLUDE_NTI))) IF @INCLUDE_NTI NOT IN ('N', 'Y') SET @INCLUDE_NTI = 'N'
--Construct a cursor to get the list of Table/Column Names according to the @TABLENAME and @COLUMNNAME parameters. SET @strSQL = N'DECLARE TabColCursor CURSOR FOR SELECT RTRIM(LTRIM(SU.NAME)) + ''.'' + LTRIM(RTRIM(SO.NAME)), SC.NAME FROM SYSOBJECTS SO INNER JOIN SYSCOLUMNS SC ON SO.ID = SC.ID INNER JOIN SYSUSERS SU ON SO.UID = SU.UID WHERE SO.XTYPE = ''U'' '
--Filter out Text/NText/Image data types if it is not included IF @INCLUDE_NTI = 'N' --In SysColumns sytem table XTYPE column corresponds to Column Data Type SET @strSQL = @strSQL + ' AND SC.XTYPE NOT IN (35, 99, 34) '
--Add the TABLE(S) name i.e. filter if it is supplied IF @TABLENAME IS NOT NULL AND ltrim(rtrim(@TABLENAME)) <> '' BEGIN SET @TABLENAME = REPLACE(@TABLENAME, ', ', ',') SET @strSQL = @strSQL + ' AND (SO.NAME LIKE ''' + REPLACE(@TABLENAME, ',', ''' OR SO.NAME LIKE ''') + ''')' END
--Add the COLUMN(S) name i.e. filter if it is supplied IF @COLUMNNAME IS NOT NULL AND ltrim(rtrim(@COLUMNNAME)) <> '' BEGIN SET @COLUMNNAME = REPLACE(@COLUMNNAME, ', ', ',') SET @strSQL = @strSQL + ' AND (SC.NAME LIKE ''' + REPLACE(@COLUMNNAME, ',', ''' OR SC.NAME LIKE ''') + ''')' END
--Execute the constructed "Cursor Declaration" string EXECUTE sp_executesql @strSQL IF @@ERROR > 0 BEGIN PRINT 'Error while declaring the Cursor. Please check out the parameters supplied to the Procedure' RETURN -1 END
--Database Transaction. BEGIN TRANSACTION gDatabaseTrans
--Open the cursor OPEN TabColCursor
--Fetch the Table, Column names to variables FETCH NEXT FROM TabColCursor INTO @sTableName, @sColumnName
--Execute the SQL statement supplied in @SQL parameter on every row of Cursor's data WHILE @@FETCH_STATUS = 0 BEGIN --Construct SQL2 to Execute supplied @SQL --by replacing @TABLENAME, @COLUMNNAME with running Table Name, Column Name of Cursor's data SET @SQL2 = @SQL SET @SQL2 = REPLACE(@SQL2, '@TABLENAME', @sTableName) SET @SQL2 = REPLACE(@SQL2, '@COLUMNNAME', @sColumnName)
--Execute the constructed SQL2 EXECUTE sp_executesql @SQL2
--Check for errors IF @@ERROR <> 0 BEGIN --On Error, Destroy objects, Rollback transaction --Return -1 as UNSUCCESSFUL flag PRINT 'Error occurred' DEALLOCATE tabcolcursor ROLLBACK TRANSACTION gDatabaseTrans RETURN -1 END
--Process Next Row of Cursor FETCH NEXT FROM TabColCursor INTO @sTableName,@sColumnName END
--Destroy CURSOR object DEALLOCATE tabcolcursor
--Procedure executed properly. Commit the Transaction. --Return 0 as SUCCESSFUL flag COMMIT TRANSACTION gDatabaseTrans RETURN 0 END