I am trying to write a stored procedure that will removed leading and trailing quotes from an arbitrary table and column. I keep getting an error saying that the table name isn't declared.
Here is the SP
create table [dbo].[test] (id nvarchar(20))
insert into dbo.test values ('"07617966004766"')
go
CREATE PROCEDURE sp_stripDoubleQuotes
#tableName sysname,
#columnName sysname
AS
BEGIN
SET NOCOUNT ON;
UPDATE #tableName
SET #columnName = SUBSTRING(#columnName, 2, LEN(#columnName))
WHERE LEFT(#columnName, 1) = '"'
UPDATE #tableName
SET #columnName = SUBSTRING(#columnName, 1, LEN(#columnName)-1)
WHERE RIGHT(#columnName, 1) = '"'
END
GO
exec [dbo].[sp_stripDoubleQuotes] N'[dbo].[test]', N'[id]'
select * from test
Here is a link to a fiddle:
link to fiddle
CREATE PROCEDURE sp_stripDoubleQuotes
#tableName sysname,
#columnName sysname,
#SQL varchar(MAX)
AS
BEGIN
SET NOCOUNT ON;
SET #SQL =
'UPDATE ' + '[' + #tableName +']' +
'SET' + '[' + #columnName +']' +'= SUBSTRING(' +'[' + #columnName +']' +', 2, LEN(' +'[' + #columnName +']' +'))
WHERE LEFT(' + '[' + #columnName +']' +', 1) = '+'''"'''
--PRINT(#SQL)
EXEC (#SQL)
SET #SQL =
'UPDATE ' + '[' + #tableName +']' +
'SET' + '[' + #columnName +']' +'= SUBSTRING(' + '[' + #columnName +']' +', 1, LEN(' + '[' + #columnName + ']' +')-1)
WHERE RIGHT(' + '[' + #columnName +']' +', 1) = '+'''"'''
--PRINT(#SQL)
EXEC (#SQL)
END
GO
exec [dbo].[sp_stripDoubleQuotes] N'test', N'id' -- exec [dbo].[sp_stripDoubleQuotes] N'[dbo].[test]', N'[id]'
Updated 2nd: I added [] to wrap table and column incase your table and column name have whitespace in them. Thanks #Sean Lange and #Richard
Updated 3rd: As #[benjamin moskovits] (xD) mentioned, if you hard coded brackets, the correct execute command is exec [dbo].[sp_stripDoubleQuotes] N'test', N'id'. Try to add or remove brackets and print to see whether the syntax is correct before executing it.
CREATE PROCEDURE sp_stripDoubleQuotes
#tableName sysname,
#columnName sysname
AS
BEGIN
SET NOCOUNT ON;
declare #QuerytoExecute varchar(1000)
set #QuerytoExecute="UPDATE "+#tableName+"
SET "+#columnName+" = SUBSTRING("+#columnName+", 2, LEN("+#columnName+"))
WHERE LEFT("+#columnName+", 1) = '""'";
exec (#QuerytoExecute);
set #QuerytoExecute="
UPDATE "+#tableName+"
SET "+#columnName+" = SUBSTRING("+#columnName+", 1, LEN("+#columnName+")-1)
WHERE RIGHT("+#columnName+", 1) = '""'";
exec (#QuerytoExecute);
END
GO
Related
I want to search in table for all records with a special characters - char(11), char(7) etc.
I have found one stored procedure which helps me to find it. But it is not accepting the input parameters as follows:
EXEC sp_FindStringInTable '%'+char(7)+'%', 'CPOA-TALENTLink-Test-Leeds', 'TALENT_Contact_ChangeLog'
Error:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '+'.
Stored procedure:
CREATE PROCEDURE dbo.sp_FindStringInTable
#stringToFind NVARCHAR(100),
#schema SYSNAME,
#table SYSNAME
AS
BEGIN TRY
DECLARE #sqlCommand VARCHAR(MAX) = 'SELECT * FROM [' + #schema + '].[' + #table + '] WHERE '
SELECT #sqlCommand = #sqlCommand + '[' + COLUMN_NAME + '] LIKE ''' + #stringToFind + ''' OR '
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = #schema
AND TABLE_NAME = #table
AND DATA_TYPE IN ('char','nchar','ntext','nvarchar','text','varchar')
SET #sqlCommand = LEFT(#sqlCommand, LEN(#sqlCommand) - 3)
EXEC (#sqlCommand)
PRINT #sqlCommand
END TRY
BEGIN CATCH
PRINT 'There was an error. Check to make sure object exists.'
PRINT error_message()
END CATCH
As mentioned in error, I'm unable to search through table for special characters.
In calls to procedures expressions other than literals or variables don't work.
Assign the concatenation to a variable and pass that variable to the procedure.
DECLARE #p varchar(max) = '%' + char(7) + '%';
EXEC sp_FindStringInTable #p, 'CPOA-TALENTLink-Test-Leeds', 'TALENT_Contact_ChangeLog';
Literal string concatenation like '[' + #schema + ']' and ' LIKE ''' + #stringToFind + '''' isn't safe. Far from it. I suspect that parametrising your query is going to fix this:
CREATE PROCEDURE dbo.sp_FindStringInTable #stringToFind NVARCHAR(100), #schema sysname, #table sysname
AS
BEGIN TRY
DECLARE #sqlCommand varchar(max);
SET #sqlCommand = N'SELECT *' + NCHAR(10) + --Formatting yoru dynamic SQL is a very good idea
N'FROM ' + QUOTENAME(#schema) + N'.' + QUOTENAME(#table) + NCHAR(10) +
N'WHERE' +
STUFF((SELECT NCHAR(10) + N' AND ' + QUOTENAME(COLUMN_NAME) + N'LIKE #String'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = #schema
AND TABLE_NAME = #table
AND DATA_TYPE IN ('char','nchar','ntext','nvarchar','text','varchar')
FOR XML PATH(N'')),1,6,N'')
PRINT #sqlCommand; --your best friend
EXEC sp_executesql #sqlCommand, N'String nvarchar(100)', #String = #stringToFind;
END TRY
BEGIN CATCH
PRINT 'There was an error. Check to make sure object exists.'
PRINT error_message()
END CATCH
Note that I have not tested the above. Your best friend is there to help you debug.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Here in sql server i want to get sql script by table name, In mysql server there is option for that SHOW CREATE TABLE client , can anyone please help how can we do this in sql server by script ?
CREATE PROCEDURE [dbo].[GENERATE_INSERTS] (#TABLENAME NVARCHAR(100),
#INCLUDE_COLUMN VARCHAR(MAX)=NULL,
#EXCLUDE_COLUMN VARCHAR(MAX) = NULL,
#TOP varchar(50)='',
#WHERECLAUSE NVARCHAR(MAX) = '',
#ORDERBYCLAUSE NVARCHAR(MAX) = '')
AS
BEGIN
SET NOCOUNT ON
--DECLARE VARIABLES
DECLARE #TABLEHASIDENTITY BIT
DECLARE #SQL NVARCHAR(MAX)
DECLARE #COLUMNLIST NVARCHAR(MAX)
DECLARE #VALUELIST NVARCHAR(MAX)
DECLARE #COLUMN_NAME VARCHAR(128)
DECLARE #DATA_TYPE VARCHAR(128)
--INITIALIZE VARIABLES
SET #COLUMNLIST = ''
SET #VALUELIST = ''
SET #COLUMN_NAME = ''
--CHECK IF THE TABLE HAS AN IDENTITY COLUMN
SELECT #TABLEHASIDENTITY = OBJECTPROPERTY(OBJECT_ID(TABLE_NAME), 'TABLEHASIDENTITY')
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = #TABLENAME
--CHECK IF WE NEED 'SET IDENTITY_INSERT TABLENAME ON' STATEMENT.
--IF THE TABLE HAS IDENTITY COLUMN, THE IDENTITY_INSERT WILL BE SET TO ON
IF #TABLEHASIDENTITY = 1
BEGIN
SET #SQL = 'SELECT TOP 1 ''SET IDENTITY_INSERT '
+ #TABLENAME + ' ON '' FROM ' + #TABLENAME
EXEC SP_EXECUTESQL
#SQL
END
--PREPARE LIST OF COLUMNS AND VALUES
--TO GET THE FIRST COLUMN'S ID
DECLARE NA_CUR CURSOR LOCAL FAST_FORWARD FOR
SELECT QUOTENAME(COLUMN_NAME),
DATA_TYPE from
INFORMATION_SCHEMA.COLUMNS C (NOLOCK)
WHERE TABLE_NAME = #TABLENAME
AND (EXISTS (SELECT TOKEN
FROM DBO.UDF_SPLITSTRING(#INCLUDE_COLUMN, ',') A WHERE C.TABLE_NAME=A.token )
--AND ( COLUMN_NAME IN (SELECT TOKEN
-- FROM DBO.UDF_SPLITSTRING(#INCLUDE_COLUMN, ','))
OR #INCLUDE_COLUMN IS NULL or #INCLUDE_COLUMN= '')
AND ( NOT EXISTS (SELECT 1
FROM DBO.UDF_SPLITSTRING(#EXCLUDE_COLUMN, ',') F
WHERE F.TOKEN = C.COLUMN_NAME)
OR #EXCLUDE_COLUMN IS NULL or #EXCLUDE_COLUMN = '' )
ORDER BY ORDINAL_POSITION ASC
OPEN NA_CUR
FETCH NA_CUR INTO #COLUMN_NAME, #DATA_TYPE
WHILE ##FETCH_STATUS = 0
BEGIN
--DETERMINING THE DATA TYPE OF THE COLUMN AND DEPENDING ON THE DATA TYPE,
--THE VALUES PART OF THE INSERT STATEMENT IS GENERATED.
SET #VALUELIST = #VALUELIST + CASE WHEN #DATA_TYPE IN ('CHAR', 'VARCHAR', 'NCHAR', 'NVARCHAR') THEN 'COALESCE('''''''' + REPLACE(RTRIM(' + #COLUMN_NAME + '),'''''''','''''''''''')+'''''''',''NULL'')'
WHEN #DATA_TYPE IN ('DATETIME', 'SMALLDATETIME') THEN 'COALESCE('''''''' + RTRIM(CONVERT(CHAR,' + #COLUMN_NAME + ',109))+'''''''',''NULL'')'
WHEN #DATA_TYPE IN ('UNIQUEIDENTIFIER') THEN 'COALESCE('''''''' + REPLACE(CONVERT(CHAR(255),RTRIM(' + #COLUMN_NAME + ')),'''''''','''''''''''')+'''''''',''NULL'')'
WHEN #DATA_TYPE IN ('TEXT', 'NTEXT') THEN 'COALESCE('''''''' + REPLACE(CONVERT(CHAR(8000),' + #COLUMN_NAME + '),'''''''','''''''''''')+'''''''',''NULL'')'
WHEN #DATA_TYPE IN ('BINARY', 'VARBINARY') THEN 'COALESCE(RTRIM(CONVERT(CHAR,' + 'CONVERT(INT,' + #COLUMN_NAME + '))),''NULL'')'
WHEN #DATA_TYPE IN ('TIMESTAMP', 'ROWVERSION') THEN 'COALESCE(RTRIM(CONVERT(CHAR,' + 'CONVERT(INT,' + #COLUMN_NAME + '))),''NULL'')'
WHEN #DATA_TYPE IN ('FLOAT', 'REAL', 'MONEY', 'SMALLMONEY') THEN 'COALESCE(LTRIM(RTRIM(' + 'CONVERT(CHAR, ' + #COLUMN_NAME + ',2)' + ')),''NULL'')'
ELSE 'COALESCE(LTRIM(RTRIM(' + 'CONVERT(CHAR, ' + #COLUMN_NAME + ')' + ')),''NULL'')' END + '+' + ''',''' + ' + '
--GENERATING THE COLUMN LIST FOR THE INSERT STATEMENT
SET #COLUMNLIST = #COLUMNLIST + #COLUMN_NAME + ','
PRINT #COLUMNLIST
PRINT #VALUELIST
FETCH NA_CUR INTO #COLUMN_NAME, #DATA_TYPE
END
CLOSE NA_CUR;
DEALLOCATE NA_CUR;
--END OF LOOP
--REMOVE EXTRA CHARACTERS THAT GOT CONCATENATED DURING THE LAST RUN THROUGH THE LOOP
SET #COLUMNLIST = LEFT(#COLUMNLIST, LEN(#COLUMNLIST) - 1)
SET #VALUELIST = LEFT(#VALUELIST, LEN(#VALUELIST) - 6)
print #COLUMNLIST
PRINT #VALUELIST
set #top = case when len(#top)>0 then 'top '+#TOP else '' end
--BUILD THE SQL STATEMENT
SET #SQL = 'SELECT '+#top+'''INSERT INTO [' + #TABLENAME + '] ('
+ #COLUMNLIST + ') ' + 'VALUES (''+' + #VALUELIST
+ '+'')'' FROM ' + #TABLENAME
--APPLY FILTER (WHERE CLAUSE) AND SORTING (ORDER BY CLAUSE) IF REQUIRED
IF LEN(#WHERECLAUSE) > 0
SET #SQL = #SQL + ' WHERE ' + #WHERECLAUSE
IF LEN(#ORDERBYCLAUSE) > 0
SET #SQL= #SQL + ' ORDER BY ' + #ORDERBYCLAUSE
--EXECUTE SQL STATEMENT TO PRINT INSERT STATEMENTS
PRINT #SQL
EXEC SP_EXECUTESQL
#SQL
--SET IDENTITY_INSERT OFF IF IT IS SET ON ABOVE
IF #TABLEHASIDENTITY = 1
BEGIN
SET #SQL = 'SELECT TOP 1 ''SET IDENTITY_INSERT '
+ #TABLENAME + ' OFF '' FROM ' + #TABLENAME
EXEC SP_EXECUTESQL
#SQL
END
END
I think the easiest way for you is using SQL Server Management studio and use the feature Generate Scripts.
More info: https://learn.microsoft.com/en-us/sql/relational-databases/scripting/generate-scripts-sql-server-management-studio
Hope it helps.
Edit:
After users feedback:
Lowell Izaguirre wrote a script that might help you. It is available on SQLServerCentral in this link http://www.sqlservercentral.com/scripts/SQL+Server+2005/67515/
Got from Here, hope it will hepl a bit.
CREATE proc GetTableScript (#table sysname)
as
declare #sql table(s varchar(1000), id int identity)
insert into #sql(s) values ('create table [' + #table + '] (')
insert into #sql(s)
select
' ['+column_name+'] ' +
data_type + coalesce('('+cast(character_maximum_length as varchar)+')','') + ' ' +
case when exists (
select id from syscolumns
where object_name(id)=#table
and name=column_name
and columnproperty(id,name,'IsIdentity') = 1
) then
'IDENTITY(' +
cast(ident_seed(#table) as varchar) + ',' +
cast(ident_incr(#table) as varchar) + ')'
else ''
end + ' ' +
( case when IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' +
coalesce('DEFAULT '+COLUMN_DEFAULT,'') + ','
from information_schema.columns where table_name = #table
order by ordinal_position
declare #pkname varchar(100)
select #pkname = constraint_name from information_schema.table_constraints
where table_name = #table and constraint_type='PRIMARY KEY'
if ( #pkname is not null ) begin
insert into #sql(s) values(' PRIMARY KEY (')
insert into #sql(s)
select ' ['+COLUMN_NAME+'],' from information_schema.key_column_usage
where constraint_name = #pkname
order by ordinal_position
update #sql set s=left(s,len(s)-1) where id=##identity
insert into #sql(s) values (' )')
end
else begin
update #sql set s=left(s,len(s)-1) where id=##identity
end
insert into #sql(s) values( ')' )
select s from #sql order by id
I wish to modify strings in several columns (for example all columns containing the 'sound' string), for example replacing ',' by '.'. Further to this post, I understand I have to use dynamic SQL. I created the following procedure:
USE [myDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[RemoveStringInColumn] (#colName varchar(50), #tableName varchar(50), #to_remove varchar(50), #to_add varchar(50))
AS
DECLARE #sql nvarchar(4000)
SET #sql = 'UPDATE ' + #tableName + ' SET ' + #colName + ' = REPLACE(' + #colName + ',' + #to_remove + ','+ #to_add + ');'
PRINT #sql
EXEC sp_executesql #sql
Which is called by:
EXEC dbo.RemoveStringInColumn 'COL_1', 'TABLE_1', ',', '.'
1) The problem is the #sql command does not contain the little hyphen arond the comma and the dot. How can I solve this?
2) In this post they use a SELECT command to fetch all column names. So far, I managed to fetch column names containing 'sound'.
select COLUMN_NAME AS my_cols
from INFORMATION_SCHEMA.COLUMNS
where table_name = 'TABLE_1' AND COLUMN_NAME LIKE '%sound%'
How can I put column names into a list and use a for loop to go through them calling the RemoveStringInColumn procedure?
Thanks
Just double the single quotes around #to_remove and #to_add
DECLARE #sql NVARCHAR(4000)
SET #sql = 'UPDATE ' + Quotename(#tableName) + ' SET ' + Quotename(#colName)
+ ' = REPLACE(' + Quotename(#colName) + ',''' + #to_remove + ''','''
+ #to_add + ''');'
PRINT #sql
EXEC Sp_executesql
#sql
Update : To do the replace for more than one column
DECLARE #sql NVARCHAR(4000),
#col_list VARCHAR(8000)= ''
SET #col_list = (SELECT ',' + Quotename(COLUMN_NAME) + ' = REPLACE('
+ Quotename(COLUMN_NAME) + ',''' + #to_remove
+ ''',''' + #to_add + ''')'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'TABLE_1'
AND COLUMN_NAME LIKE '%sound%'
FOR xml path(''))
SET #col_list = Stuff(#col_list, 1, 1, '')
SELECT #col_list
SET #sql = 'UPDATE ' + Quotename(#tableName) + ' SET '
+ #col_list
PRINT #sql
EXEC Sp_executesql
#sql
I've got error:
Must declare the scalar variable #columns
Where is the problem? Thank you
ALTER PROCEDURE CreateTable
#tabname nvarchar(max)
as
declare #columns nvarchar(max) = null;
declare #sql nvarchar(max) = null;
select #columns=coalesce(#columns + ', ')
+colname
+ ' '
+coltype
from x_column
where colname is not null
and tabname=#tabname
order by colnum;
set #sql =IF NOT EXISTS (SELECT * FROM sys.objects WHERE
object_id=OBJECT_ID(N'[#tabname]') AND type in (N'U'))
create table ' + #tabname + ' (' + #columns + ');
print #sql;
-- execute create table
exec sp_sqlexec #sql;
GO
Try like this,
ALTER PROCEDURE CreateTable #tabname NVARCHAR(max)
AS
DECLARE #columns NVARCHAR(max) = NULL;
DECLARE #sql NVARCHAR(max) = NULL;
SELECT #columns = coalesce(#columns, ', ') + colname + ' ' + coltype
FROM x_column
WHERE colname IS NOT NULL
AND tabname = #tabname
ORDER BY colnum;
SET #sql = 'IF NOT EXISTS (SELECT * FROM sys.objects WHERE
object_id=OBJECT_ID(N[' + #tabname + ']) AND type in (N''U''))
create table [' + #tabname + '] (' + #columns + ');'
PRINT #sql;
-- execute create table
EXEC sp_sqlexec #sql;
GO
Syntax error with coalesce and for #sql the data is not loaded properly
So the below script will work:
alter PROCEDURE CreateTable
#tabname nvarchar(max)
as
declare #columns nvarchar(max) = null;
declare #sql nvarchar(max) = null;
select #columns = coalesce(#columns , ', ') + colname + ' ' + coltype
from x_column
where colname is not null
and tabname = #tabname
order by colnum;
set #sql = 'IF NOT EXISTS ( SELECT * FROM sys.objects WHERE
object_id = OBJECT_ID(N[' + #tabname + ']) AND type in (N''U''))
create table ' + #tabname + ' (' + #columns + ');'
print #sql;
-- execute create table
exec sp_sqlexec #sql;
GO
Change your query like this:
ALTER PROCEDURE CreateTable
#tabname nvarchar(max)
as
declare #columns nvarchar(max) = null;
declare #sql nvarchar(max) = null;
SELECT #columns = STUFF((SELECT ',' + colname + ' ' + coltype
FROM x_column
WHERE colname IS NOT NULL
AND tabname = #tabname
ORDER BY colnum
FOR XML PATH('')),1,1,'')
set #sql ='IF NOT EXISTS (SELECT * FROM sys.objects WHERE
object_id=OBJECT_ID(N['+#tabname+']) AND type in (N''U''))
create table [' + #tabname + '] (' + #columns + ');'
print #sql;
-- execute create table
exec sp_sqlexec #sql;
GO
use this
set #sql ='IF NOT EXISTS (SELECT * FROM sys.objects WHERE
object_id=OBJECT_ID('+#tabname+') AND type in (''U''))
create table ' + #tabname + ' (' + #columns + ')';`
Question is pretty self explanitory. I want to do a simple find and replace, like you would in a text editor on the data in a column of my database (which is MsSQL on MS Windows server 2003)
The following query replace each and every a character with a b character.
UPDATE
YourTable
SET
Column1 = REPLACE(Column1,'a','b')
WHERE
Column1 LIKE '%a%'
This will not work on SQL server 2003.
like so:
BEGIN TRANSACTION;
UPDATE table_name
SET column_name=REPLACE(column_name,'text_to_find','replace_with_this');
COMMIT TRANSACTION;
Example: Replaces <script... with <a ... to eliminate javascript vulnerabilities
BEGIN TRANSACTION; UPDATE testdb
SET title=REPLACE(title,'script','a'); COMMIT TRANSACTION;
This pointed me in the right direction, but I have a DB that originated in MSSQL 2000 and is still using the ntext data type for the column I was replacing on. When you try to run REPLACE on that type you get this error:
Argument data type ntext is invalid for argument 1 of replace
function.
The simplest fix, if your column data fits within nvarchar, is to cast the column during replace. Borrowing the code from the accepted answer:
UPDATE YourTable
SET Column1 = REPLACE(cast(Column1 as nvarchar(max)),'a','b')
WHERE Column1 LIKE '%a%'
This worked perfectly for me. Thanks to this forum post I found for the fix. Hopefully this helps someone else!
The following will find and replace a string in every database (excluding system databases) on every table on the instance you are connected to:
Simply change 'Search String' to whatever you seek and 'Replace String' with whatever you want to replace it with.
--Getting all the databases and making a cursor
DECLARE db_cursor CURSOR FOR
SELECT name
FROM master.dbo.sysdatabases
WHERE name NOT IN ('master','model','msdb','tempdb') -- exclude these databases
DECLARE #databaseName nvarchar(1000)
--opening the cursor to move over the databases in this instance
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #databaseName
WHILE ##FETCH_STATUS = 0
BEGIN
PRINT #databaseName
--Setting up temp table for the results of our search
DECLARE #Results TABLE(TableName nvarchar(370), RealColumnName nvarchar(370), ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE #SearchStr nvarchar(100), #ReplaceStr nvarchar(100), #SearchStr2 nvarchar(110)
SET #SearchStr = 'Search String'
SET #ReplaceStr = 'Replace String'
SET #SearchStr2 = QUOTENAME('%' + #SearchStr + '%','''')
DECLARE #TableName nvarchar(256), #ColumnName nvarchar(128)
SET #TableName = ''
--Looping over all the tables in the database
WHILE #TableName IS NOT NULL
BEGIN
DECLARE #SQL nvarchar(2000)
SET #ColumnName = ''
DECLARE #result NVARCHAR(256)
SET #SQL = 'USE ' + #databaseName + '
SELECT #result = MIN(QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME))
FROM [' + #databaseName + '].INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = ''BASE TABLE'' AND TABLE_CATALOG = ''' + #databaseName + '''
AND QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME) > ''' + #TableName + '''
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME)
), ''IsMSShipped''
) = 0'
EXEC master..sp_executesql #SQL, N'#result nvarchar(256) out', #result out
SET #TableName = #result
PRINT #TableName
WHILE (#TableName IS NOT NULL) AND (#ColumnName IS NOT NULL)
BEGIN
DECLARE #ColumnResult NVARCHAR(256)
SET #SQL = '
SELECT #ColumnResult = MIN(QUOTENAME(COLUMN_NAME))
FROM [' + #databaseName + '].INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(''[' + #databaseName + '].' + #TableName + ''', 2)
AND TABLE_NAME = PARSENAME(''[' + #databaseName + '].' + #TableName + ''', 1)
AND DATA_TYPE IN (''char'', ''varchar'', ''nchar'', ''nvarchar'')
AND TABLE_CATALOG = ''' + #databaseName + '''
AND QUOTENAME(COLUMN_NAME) > ''' + #ColumnName + ''''
PRINT #SQL
EXEC master..sp_executesql #SQL, N'#ColumnResult nvarchar(256) out', #ColumnResult out
SET #ColumnName = #ColumnResult
PRINT #ColumnName
IF #ColumnName IS NOT NULL
BEGIN
INSERT INTO #Results
EXEC
(
'USE ' + #databaseName + '
SELECT ''' + #TableName + ''',''' + #ColumnName + ''',''' + #TableName + '.' + #ColumnName + ''', LEFT(' + #ColumnName + ', 3630)
FROM ' + #TableName + ' (NOLOCK) ' +
' WHERE ' + #ColumnName + ' LIKE ' + #SearchStr2
)
END
END
END
--Declaring another temporary table
DECLARE #time_to_update TABLE(TableName nvarchar(370), RealColumnName nvarchar(370))
INSERT INTO #time_to_update
SELECT TableName, RealColumnName FROM #Results GROUP BY TableName, RealColumnName
DECLARE #MyCursor CURSOR;
BEGIN
DECLARE #t nvarchar(370)
DECLARE #c nvarchar(370)
--Looping over the search results
SET #MyCursor = CURSOR FOR
SELECT TableName, RealColumnName FROM #time_to_update GROUP BY TableName, RealColumnName
--Getting my variables from the first item
OPEN #MyCursor
FETCH NEXT FROM #MyCursor
INTO #t, #c
WHILE ##FETCH_STATUS = 0
BEGIN
-- Updating the old values with the new value
DECLARE #sqlCommand varchar(1000)
SET #sqlCommand = '
USE ' + #databaseName + '
UPDATE [' + #databaseName + '].' + #t + ' SET ' + #c + ' = REPLACE(' + #c + ', ''' + #SearchStr + ''', ''' + #ReplaceStr + ''')
WHERE ' + #c + ' LIKE ''' + #SearchStr2 + ''''
PRINT #sqlCommand
BEGIN TRY
EXEC (#sqlCommand)
END TRY
BEGIN CATCH
PRINT ERROR_MESSAGE()
END CATCH
--Getting next row values
FETCH NEXT FROM #MyCursor
INTO #t, #c
END;
CLOSE #MyCursor ;
DEALLOCATE #MyCursor;
END;
DELETE FROM #time_to_update
DELETE FROM #Results
FETCH NEXT FROM db_cursor INTO #databaseName
END
CLOSE db_cursor
DEALLOCATE db_cursor
Note: this isn't ideal, nor is it optimized
If you are working with SQL Server 2005 or later there is also a CLR library available at http://www.sqlsharp.com/ that provides .NET implementations of string and RegEx functions which, depending on your volume and type of data may be easier to use and in some cases the .NET string manipulation functions can be more efficient than T-SQL ones.