I tried to compose a string to execute in SQL Server:
DECLARE #sql varchar(4000) =
'EXEC sys.sp_addextendedproperty #name=N''MS_Description'', #value=N''' + 'описание' + ''', #level0type=N''SCHEMA'',#level0name=N''' + 'rudata_r2' + ''', #level1type=N''TABLE'',#level1name=N''' + 'Subscriptions' + ''', #level2type=N''COLUMN'',#level2name=N''' + 'id' + '''' + char(13) + char(10) + 'GO'
EXEC(#sql)
but I got an error:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near 'GO'
Where is my mistake?
Thanks big to all. I have fixed the problem by changed GO to semicolon. Thanks again
Related
I am trying to use OPENQUERY with dynamic variables. I tried to create a query string like this;
DECLARE #SQL nvarchar(MAX);
DECLARE #CRLF nchar(2) = NCHAR(13) + NCHAR(10);
SET #SQL = N'{SELECT * INTO #tmpTable}' + #CRLF +
N'FROM OPENQUERY("my_source_ip", ''EXEC [DB].dbo.SP_inventory' + CONVERT(varchar(10),#StoreId) + ',' + QUOTENAME(CONVERT(varchar,#StartDate,112)) + ',' + QUOTENAME(CONVERT(varchar,#EndDate,112)) +')';
However, I have got following errors;
Msg 102, Level 15, State 1, Line 7
Incorrect syntax near '{'.
Msg 102, Level 15, State 1, Line 7
Incorrect syntax near '}'.
Msg 105, Level 15, State 1, Line 8
Unclosed quotation mark after the character string 'EXEC [DB].dbo.SP_inventory8005,[20170101],[20190707]'.
How can I fix this query string to work correctly? Thanks.
You have an extra "," after stored procedure name. I have replaced it with blank space. Please try this.
DECLARE #SQL nvarchar(MAX);
DECLARE #CRLF nchar(2) = NCHAR(13) + NCHAR(10);
SET #SQL = N'{SELECT * INTO #tmpTable}' + #CRLF +
N'FROM OPENQUERY("my_source_ip", ''EXEC [DB].dbo.SP_inventory' +
CONVERT(varchar(10),#StoreId) + ' ' + QUOTENAME(CONVERT(varchar,#StartDate,112)) + ','
+ QUOTENAME(CONVERT(varchar,#EndDate,112)) +')';
I have the below T SQL statement but keep getting the error
Incorrect syntax near the keyword 'CONVERT'
Where am I going wrong?
DECLARE #NSQL2 NVARCHAR(MAX)
DECLARE #SOURCETABLE NVARCHAR(MAX)
SELECT TOP 1 #SOURCETABLE = TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE 'IN_PRODUCT________________%'
AND TABLE_TYPE = 'BASE TABLE'
SET #NSQL2 = 'UPDATE [' + #SOURCETABLE + '] SET OnSale = '''+ CONVERT(nvarchar(MAX),OnSale, 112)+'''
EXEC SP_EXECUTESQL #NSQL2
Try this:
SET #NSQL2 = 'UPDATE ' + QUOTENAME(#SOURCETABLE)
+ ' SET OnSale = CONVERT(nvarchar(10),OnSale, 112)'
I got it to work using the below:
SET #NSQL = 'UPDATE [' + #SOURCETABLE + '] SET OnSale = CONVERT(nvarchar,CAST(OnSale AS DATETIME), 120)'
Did you intend for the Convert statement to be part of your string as a literal?
SET #NSQL2 = 'UPDATE [' + #SOURCETABLE + '] SET OnSale = CONVERT(nvarchar(MAX),OnSale, 112)'
I am building a dynamic T-SQL script and running into some errors.
PRINT 'Convert References into XML fields'
SET #query = N';WITH DCODES AS (' +
'SELECT [id],[Codes],' +
'CAST(''<M>'' + REPLACE([Codes],'','' , ''</M><M>'') + ''</M>'' AS XML) AS [XML_Codes],' +
'CAST(''<M>'' + REPLACE(REPLACE([Descriptions],''&'',''AND''),'','',''</M><M>'') + ''</M>'' AS XML) AS [XML_Desc] ' +
'FROM ##' + #system_name + '_Temp)'
EXEC sp_executesql #query
The code works if I write the statement as a static statement. When I run this in my dynamic script this error.
--Msg 102, Level 15, State 1, Line 1
--Incorrect syntax near ')'.
I tried to rewrite it, but I still get this issue.
missing line below
SET #query = N';WITH DCODES AS (' +
'SELECT [id],[Codes],' +
'CAST(''<M>'' + REPLACE([Codes],'','' , ''</M><M>'') + ''</M>'' AS XML) AS [XML_Codes],' +
'CAST(''<M>'' + REPLACE(REPLACE([Descriptions],''&'',''AND''),'','',''</M><M>'') + ''</M>'' AS XML) AS [XML_Desc] ' +
'FROM ##' + #system_name + '_Temp) select * from DCODES' -- you are missing this
Following is a part of my instead of update trigger
CREATE TRIGGER TestDemo ON Consultants1
INSTEAD OF UPDATE
AS
DECLARE #Sql nvarchar(200),
#TableName nvarchar(50),
#FieldName nvarchar(100),
#PKCols VARCHAR(1000), --Primary Key
#Value nvarchar(100)
SET #TableName = 'Consultants1'
SET #FieldName = 'DisplayName'
SET #Value = 'Test123'
SELECT * INTO #ins FROM inserted
SELECT #PKCols = c.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
WHERE pk.TABLE_NAME = #TableName
AND CONSTRAINT_TYPE = 'PRIMARY KEY'
AND c.TABLE_NAME = pk.TABLE_NAME
AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
SELECT #Sql = 'UPDATE ' + #TableName + ' SET '
SELECT #Sql = #Sql + #FieldName + ' = ''' + #Value + ''''
SELECT #Sql = #Sql + ' WHERE #ins.' + #PKCols + ' = ' + #TableName + '.' + #PKCols
EXEC (#Sql)
The trigger gets created without any errors.
Now I am trying to execute the following query
UPDATE Consultants1 SET DisplayName = 'abcd'
where ConsIntID = 'Test123285'
It gives a error saying:
Msg 4104, Level 16, State 1, Line 1
The multi-part identifier "#ins.ConsIntID" could not be bound.
I could not understand where my code goes wrong. Please help
You may change this line of code
SELECT #Sql = #Sql + ' WHERE #ins.' + #PKCols + ' = ' + #TableName + '.' + #PKCols
to this
SELECT #Sql = #Sql + ' FROM #ins a INNER JOIN ' + #TableName + ' b ON a.' + #PKCols + ' = b.' + #PKCols
Another story is that after the change you'll probably receive an error: Msg 570, Level 16, State 1, Line 1
INSTEAD OF triggers do not support direct recursion. The trigger execution failed.
Here's a good article about INSTEAD OF triggers and recursion in MSDN. Check the Remarks section.
I'm new to SQLServer scripting (normally being a C++ developer), and would really appreciate a bit of assistance.
I am attempting to perform a "find and replace" update on all tables in a SQLServer database that contain a 'PROJID' column. I am really struggling to find a way to do this that doesn't report to me:
Msg 207, Level 16, State 1, Line 1 Invalid column name 'PROJID'.
The statement I am executing is:
EXEC
(
'IF EXISTS(SELECT * FROM sys.columns WHERE name = N''PROJID'' AND Object_ID = Object_ID(N''' + #TableName + '''))' +
' BEGIN' +
' UPDATE ' + #TableName +
' SET ' + #ColumnName + ' = REPLACE(' + #ColumnName + ',''' + #ReplaceIDStr + ''',''' + #FindIDStr + ''')' +
' WHERE ' + #ColumnName + ' LIKE ''' + #ReplaceIDStr + '''' + ' AND PROJID = ''1000''' +
' END'
)
I have also tried using:
'IF COL_LENGTH(''' + #TableName + ''',''PROJID'') IS NOT NULL' +
instead of the column-exist check above. This also still gives me the "Invalid Column Name" messages.
I would be happy to take the column-exist check outside of the 'Exec' statement, but I'm not sure how to go about doing this either.
You just need to do it in a different scope.
IF EXISTS (SELECT 1 FROM sys.columns ...)
BEGIN
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'UPDATE ...';
EXEC sp_executesql #sql;
END
Output the results of this query to text. Don't forget to change the values of the variables! Take the result of this and run it.
SET NOCOUNT ON
DECLARE #ColumnName VARCHAR(200) = 'ReplaceColumn'
, #ReplaceIdStr VARCHAR(200) = 'ExampleReplaceIdStr'
, #FindIdStr VARCHAR(200) = 'ExampleFindIdStr'
PRINT 'BEGIN TRAN'
PRINT 'SET XACT_ABORT ON'
SELECT
'UPDATE ' + C.TABLE_NAME + CHAR(13)
+ 'SET ' + #ColumnName + ' = REPLACE(' + #ColumnName + ', ''' + #ReplaceIdStr + ''', ''' + #FindIdStr + ''')' + CHAR(13)
+ 'WHERE ' + #ColumnName + ' LIKE ''%' + #ReplaceIdStr + '%'' AND PROJID = ''1000''' + CHAR(13)
FROM INFORMATION_SCHEMA.COLUMNS C
WHERE C.COLUMN_NAME = 'PROJID'
PRINT 'COMMIT TRAN'
SET NOCOUNT OFF
EDIT: Also, some reasoning: You said you want update all tables where they contain a column called PROJID. Your first query just says that if the table #TableName has a PROJID column, then update #ColumnName on it. But it doesn't guarantee that it has #ColumnName on it. The query I gave doesn't check that either, because I'm assuming that all tables that have PROJID also have #ColumnName. If that isn't the case, let me know and I can update the answer to check that. That you're getting an Invalid Column Name error points to #ColumnName not existing.
Your query would have updated one table (#TableName) at most, whereas the one I gave you will update every table that has PROJID. I hope that's what your going for.
EDIT 2: Here is a version that would run it all at once:
DECLARE #ColumnName VARCHAR(200) = 'Value'
, #ReplaceIdStr VARCHAR(200) = 'ExampleReplaceIdStr'
, #FindIdStr VARCHAR(200) = 'ExampleFindIdStr'
DECLARE #Sql NVARCHAR(MAX)
DECLARE UpdateCursor CURSOR FOR
SELECT
'UPDATE ' + C.TABLE_NAME
+ ' SET ' + #ColumnName + ' = REPLACE(' + #ColumnName + ', ''' + #ReplaceIdStr + ''', ''' + #FindIdStr + ''')'
+ ' WHERE ' + #ColumnName + ' LIKE ''%' + #ReplaceIdStr + '%'' AND PROJID = ''1000'''
FROM INFORMATION_SCHEMA.COLUMNS C
WHERE C.COLUMN_NAME = 'PROJID'
OPEN UpdateCursor
FETCH NEXT FROM UpdateCursor
INTO #Sql
WHILE ##FETCH_STATUS = 0
BEGIN
EXEC sp_executesql #Sql
FETCH NEXT FROM UpdateCursor
INTO #Sql
END
CLOSE UpdateCursor
DEALLOCATE UpdateCursor