how to do a search and replace for a string in mssql 2012 - sql

I am having to find and replace a substring over all columns in all tables in a given database.
I tried this code from sqlserver 2012 ssms but resulting in errors from http://www.dbtalks.com/uploadfile/anjudidi/find-and-replace-string-values-in-all-tables-and-column-in-s/ Find and Replace string Values in All Tables and column in SQL Serve
I think its for older version, it having problems with some of the tables names that start with a number: example dbo.123myTable
Appreciate all the help in advance
Error Print:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '.153'.
UPDATE dbo.153Test2dev SET [ALCDescription] = REPLACE(convert(nvarchar(max),[ALCDescription]),'TestsMT','Glan') WHERE [ALCDescription] LIKE '%SherlinMT%'
Updated: 1
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '.153'.
UPDATE dbo.153TypeTest2 SET [FormTypeDescription] = REPLACE(convert(nvarchar(max),[FormTypeDescription]),'TestsMT','Glan') WHERE [FormTypeDescription] LIKE '%SherlinMT%'
Updated: 1

Just as a guess, to add delimiters to your table names, modify the script you linked to by editing this line:
SET #sqlCommand = 'UPDATE ' + #schema + '.' + #table + ' SET [' + #columnName + '] = REPLACE(convert(nvarchar(max),[' + #columnName + ']),''' + #stringToFind + ''',''' + #stringToReplace + ''')'
and change it to
SET #sqlCommand = 'UPDATE [' + #schema + '].[' + #table + '] SET [' + #columnName + '] = REPLACE(convert(nvarchar(max),[' + #columnName + ']),''' + #stringToFind + ''',''' + #stringToReplace + ''')'

Are you sure table names may begin with a digit? If so, include them in '[' ']', like
UPDATE [dbo].[153TypeTest2].....

based in the code you linked to, try this:
SET #sqlCommand = 'UPDATE [' + #schema + '].[' + #table + '] SET [' + .....
--add square braces: ^ ^ ^ ^

You should bracket your table name in the same way as the column name in the update query (see #table now has brackets):
SET #sqlCommand = 'UPDATE ' + #schema + '.[' + #table + '] SET [' + #columnName + '] =
REPLACE(convert(nvarchar(max),[' + #columnName + '])

Related

Modify columns using stored procedure in SQL Server

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

How to display the output and also save it in global temp table in ms-sql

Usually when we use select statement it displays the output, but when insert into is used,stores the result into temp table.i want to do both.Display result and store in temp table as well in dynamic sql.
IF #DisplayInSelect IS NOT NULL
SET #DisplayInSelect = ','+#DisplayInSelect
SET #SQL = 'IF EXISTS (SELECT DISTINCT a.'+#column_name+' FROM ['+#TableName+'] a where '+#FullCondition+' )'+
'SELECT DISTINCT ''Error at column: '+#Column_name+''' as [Error Records if found any are shown below],'''+ISNULL(#CustomErrorMessage,'ERROR')+''''+ISNULL(#DisplayInSELECT,'')+', a.'+#column_name+',* FROM ['+#TableName+'] a where '+#FullCondition+'
INSERT INTO ##error_check(SELECT DISTINCT ''Error at column: '+#Column_name+''' as [Error Records if found any are shown below],'''+ISNULL(#CustomErrorMessage,'ERROR')+''''+ISNULL(#DisplayInSELECT,'')+', a.'+#column_name+', *FROM ['+#TableName+'] a where '+#FullCondition+');
PRINT('IQR1 sql is'+#SQL)
EXEC(#SQL)
END
You have to use insert into table along with Exec. Try like this,
IF #DisplayInSelect IS NOT NULL
SET #DisplayInSelect = ',' + #DisplayInSelect
SET #SQL = 'IF EXISTS (SELECT DISTINCT a.' + #column_name + ' FROM [' + #TableName + '] a where ' + #FullCondition + ' )' + 'SELECT DISTINCT ''Error at column: ' + #Column_name + ''' as [Error Records if found any are shown below],''' + ISNULL(#CustomErrorMessage, 'ERROR') + '''' + ISNULL(#DisplayInSELECT, '') + ', a.' + #column_name + ',* FROM [' + #TableName + '] a where ' + #FullCondition + '
SELECT DISTINCT ''Error at column: ' + #Column_name + ''' as [Error Records if found any are shown below],''' + ISNULL(#CustomErrorMessage, 'ERROR') + '''' + ISNULL(#DisplayInSELECT, '') + ', a.' + #column_name + ', *FROM [' + #TableName + '] a where ' + #FullCondition + ';'
--To Save
INSERT INTO ##error_check
EXEC (#SQL)
PRINT (' IQR1 sql IS ' + #SQL)
--To Display
EXEC (#SQL)

sql dynamic variables are not executing? [duplicate]

This question already has answers here:
Incorrect syntax near ']'.?
(3 answers)
Closed 8 years ago.
After trying to find out the problem myself doing some debugging
I have found that #cols and #cols2 variables are not bringing a result , I have PRINT
PRINT('INSERT INTO [' + #Destination_Database_Name + '].[dbo].[' + #tablename + '] (' + #cols2 + ']' + ') SELECT [' + #cols2 + ']' + ' FROM [' + #Source_Database_Name + '].[dbo].[' + #tablename + ']');
And the statement will not show the output all I get is
(1 row(s) affected)
(1 row(s) affected)
I am here2
c365online_script1
I am here3
tCompany
This is the section of the code which I think is the problem
Print 'I am here2'
SET IDENTITY_INSERT c365online_script1.dbo.tCompany ON
declare #cols2 varchar(max)
PRINT #cols2
select #cols2 = (Select Stuff((Select '],[' + C.COLUMN_NAME From INFORMATION_SCHEMA.COLUMNS As C Where C.TABLE_SCHEMA = T.TABLE_SCHEMA And C.TABLE_NAME = T.TABLE_NAME Order By C.ORDINAL_POSITION For Xml Path('')), 1, 2, '') As Columns From INFORMATION_SCHEMA.TABLES As T WHERE T.TABLE_NAME = #tablename)
PRINT('INSERT INTO [' + #Destination_Database_Name + '].[dbo].[' + #tablename + '] (' + #cols2 + ']' + ') SELECT [' + #cols2 + ']' + ' FROM [' + #Source_Database_Name + '].[dbo].[' + #tablename + ']');
PRINT #Destination_Database_Name
Print 'I am here3'
Print #tablename
END
I can post full code on request
Try
SET #cols2 = (Select....)
instead of
SELECT #cols2 = (Select....)
This is a NULL concatenation problem. Try initializing your variables as empty strings, like this, and see what you learn about the results of your query:
declare #tablename varchar(128) = '',
#Destination_Database_Name varchar(128) = '',
#Source_Database_Name varchar(128) = '';

How to run INstead of trigger on all my tables in my database with even field?

i just want to use a trigger instead of insert and update to run on all my tables?
how to do it?
please help me
In SQL Server you can use triggers on DML operations (so per table) as well as on the entire database (DDL trigger). I imagine the syntax is more or less the same for other systems.
The syntax for the first is:
CREATE TRIGGER name ON table
[FOR/AFTER/INSTEAD OF]
[INSERT, UPDATE, DELETE]
AS
BEGIN
--SQL statements
...
END
DDL triggers are not used as much, mostly for auditing but there are better ways to do audit. Anyway, check out this article with some examples.
Sound like it is necessary to create trigger for each table in your database. You can dynamically create a SQL statement on the tables loop and then run that command.
Simple example (Output results in text format)
DECLARE #triggerName nvarchar(50) = 'triggerName'
SELECT 'IF OBJECT_ID(''' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + QUOTENAME(#triggerName) + ''')' +
' IS NOT NULL DROP TRIGGER ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' +
QUOTENAME(#triggerName) + CHAR(13) + CHAR(10) +
'GO' + CHAR(13) + CHAR(10) +
'CREATE TRIGGER ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' +
QUOTENAME(#triggerName) + ' ON ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' +
QUOTENAME(OBJECT_NAME(object_id)) + CHAR(13) + CHAR(10) +
'INSTEAD OF INSERT, UPDATE' + CHAR(13) + CHAR(10) +
'AS' + CHAR(13) + CHAR(10) +
'BEGIN' + CHAR(13) + CHAR(10) +
' SELECT ''your_logic''' + CHAR(13) + CHAR(10) +
'END' + CHAR(13) + CHAR(10) +
'GO' + CHAR(13) + CHAR(10) +
'' + CHAR(13) + CHAR(10)
FROM sys.tables

Script all data out of a single table or all tables in Sql Server 2005/8?

Simple question here, and I know there are lots of kludgy ways to do it :)
But I was hoping a SQL server expert had a script to easily script all the data out of a table? Or possibly all the tables in a DB?
I'm getting tired of copying and pasting data over RDC! :)
I had a similar requirement.
To script insert statements for each row in a table. Sometimes I needed the Identity column, other times I did not.
So, I wrote this:
CREATE PROCEDURE [dbo].[GenerateInsertScripts] (
#tableName varchar(100),
#tableSchema varchar(50) = 'dbo',
#skipIdentity bit = 1
)
AS
BEGIN
DECLARE #columnName varchar(800)
DECLARE #columnType varchar(20)
DECLARE #statementA varchar(MAX)
DECLARE #statementB varchar(MAX)
DECLARE #statement nvarchar(MAX)
DECLARE #isIdentity bit
DECLARE #commaFlag bit
SET #statementA = 'INSERT INTO [' + #tableSchema + '].[' + #tableName + '] ('
SET #statementB = ''' + '
DECLARE cols CURSOR FOR
SELECT
COLUMN_NAME,
DATA_TYPE,
(SELECT COLUMNPROPERTY(OBJECT_ID('[' + #tableSchema + '].[' + #tableName + ']'),
information_schema.columns.COLUMN_NAME, 'IsIdentity')) AS IsIdentity
FROM
information_schema.columns
WHERE
TABLE_NAME = #tableName
AND
TABLE_SCHEMA = #tableSchema
ORDER BY
ORDINAL_POSITION
OPEN cols
FETCH cols INTO #columnName, #columnType, #isIdentity
SET #commaFlag = 0
WHILE ##FETCH_STATUS = 0
BEGIN
IF NOT (#isIdentity = 1 AND #skipIdentity = 1) BEGIN
IF #commaFlag = 1 BEGIN
SET #statementA = #statementA + ', '
SET #statementB = #statementB + ' + '', '' + '
END
SET #commaFlag = 1
SET #statementA = #statementA + '[' + #columnName + ']'
SET #statementB = #statementB + 'CASE WHEN [' + #columnName + '] IS NULL THEN ''NULL'' ELSE ' +
CASE
WHEN #columnType = 'bigint' OR #columnType = 'int' OR #columnType = 'tinyint' OR #columnType = 'bit' THEN
'CAST([' + #columnName + '] AS varchar(MAX))'
WHEN #columnType = 'datetime' THEN
''''''''' + CONVERT(varchar, [' + #columnName + '], 121) + '''''''''
ELSE
''''''''' + REPLACE(CAST([' + #columnName + '] AS varchar(MAX)), '''''''', '''''''''''') + '''''''''
END
+ ' END'
END
FETCH cols INTO #columnName, #columnType, #isIdentity
END
SET #commaFlag = 0
CLOSE cols
DEALLOCATE cols
SET #statementB = #statementB + ' + '''
SET #statement = 'SELECT ''' + #statementA + ') VALUES (' + #statementB + ')'' [Statement] FROM [' + #tableSchema + '].[' + #tableName + ']'
EXEC sp_executesql #statement
END
use this great script:
http://vyaskn.tripod.com/code.htm#inserts
but this is a bad way to move data, good to help fix a problem or move a little test data etc.
If you are moving data to a differnt database or some sort of file, use SSIS. IF the task is not complex, use the wizard, right click onthe datbasename, go to taks and choose Export data.
If you are doing the whole database an alternative is to simply restore the latest backup in the other location.
For SQL Server 2008 you can use the Script Data option in the Generate Scripts wizard. Not for 2005 though.
You can start the wizard by right clicking on a database in the Object Explorer in SSMS, and then Tasks -> Generate Scripts....
For SQL Server 2005, you can use the free Database Publishing Wizard from Microsoft.