Dynamic T-SQL WITH Statement Error - sql-server

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

Related

What's wrong with string?

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

Can't figure out the correct quotation mark structure for a sql string

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)) +')';

T-sql and json and XML

Does anybody know how to get intellisense working in query windows in SSMS for JSON methods?
I'm just getting started with querying from remote databases and for some reason when I attempt to type in methods, e.g., isjson() in the t-sql editor, not showing any of the functions.
Do I need to import any packages?
You can use Json Format by create this procedure :
CREATE PROCEDURE [dbo].[sp_query_json]
#query nvarchar(4000)
AS
BEGIN
SET NOCOUNT ON;
Declare #query_adjust nvarchar(max)
set #query_adjust = 'select ' + '''['''
+ ' + replace(replace(replace(replace(replace(('
+ #query + ' for xml raw ),'
+ '''<row ''' + ',' + '''{"''' + '),'
+ '''/>''' + ',' + '''},''' + '),'
+ '''" ''' + ',' + '''","''' + '),'
+ '''="''' + ',' + '''":"''' + ') + '
+ ''']''' + ','
+ ''',]''' + ',' + ''']''' + ')'
EXECUTE sp_executesql #query_adjust
END
You can test query like that :
EXECUTE [dbo].[sp_query_json] 'select id,name from table'
this call real Table or View and change it to XML by using
For XML RAW
And replace XML tags to JSON like

Error in my stored procedure

I created a stored procedure as follows:
create procedure [dbo].[ModifCodMedecin] #Table nvarchar(10),#Code nvarchar(7) as
DECLARE #rqt as NVARCHAR(4000)
SET #rqt = 'UPDATE' + #Table + 'SET '+ #Code + ' = Med.New_Code_exploitation from ' + #Table +
' inner join Medecin_New Med on ' + #Table + '.' + #Code + ' = Med.[Ancien_Code])'
exec (#rqt)
When I executed the above, an error is produced:
ModifCodMedecin 'Table','code'
Incorrect syntax near '='.
Try this:
CREATE PROCEDURE [dbo].[ModifCodMedecin] #Table NVARCHAR(10)
,#Code NVARCHAR(7)
AS
DECLARE #rqt AS NVARCHAR(4000)
SET #rqt = 'UPDATE ' + #Table
+ ' SET ' + #Code
+ ' = Med.New_Code_exploitation from ' + #Table
+ ' inner join Medecin_New Med on ' + #Table + '.' + #Code
+ ' = Med.[Ancien_Code]'
EXEC (#rqt)
You had a few missing spaces, one after UPDATE and one before SET. As well as the additional parenthesis at the end.

SQLServer conditional execution within 'EXEC' if a column exists

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

Resources