I have done some debugging on my sql and I cant figure out the maddening error I am getting I have narrowed it down to a couple of lines which I cant see what the problem is, please someone give me some assistance.
I get this error
I am here2
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near
']'.
I am here3
Print 'I am here2'
SET IDENTITY_INSERT c365online_script1.dbo.tCompany ON
declare #cols2 varchar(max)
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)
EXEC('INSERT INTO [' + #Destination_Database_Name + '].[dbo].[' + #tablename + '] (' + #cols2 + ']' + ') SELECT ' + #cols2 + ']' + ' FROM [' + #Source_Database_Name + '].[dbo].[' + #tablename + ']');
Print 'I am here3'
You're missing an opening square bracket here:
... ') SELECT ' + #cols2 + ']' + ' FROM ...
Furthermore I would recommend you switch to using the QuoteName() function instead:
... ') SELECT ' + QuoteName(#cols2) + ' FROM...
You are missing about 3 opening brackets as far as i can tell at
select #cols2 = (Select Stuff((Select '],[
and
(' + #cols2 + ']' // -> either [' + #cols2 + ']' or (' + #cols2 + ')'
and
+ ') SELECT ' + #cols2 + ']' -- -> either ') SELECT [' + #cols2 + ']' or ') SELECT (' + #cols2 + ')'
declare #cols2 nvarchar(max)
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, 1, '') As Columns
From INFORMATION_SCHEMA.TABLES As T
WHERE T.TABLE_NAME = #tablename)
Edit
DECLARE #Destination_Database_Name NVARCHAR(128) = 'Trg_DataBaseName'
DECLARE #tablename NVARCHAR(128) = 'AgressoIFCGLItems'
DECLARE #Source_Database_Name NVARCHAR(128) = 'Configsandpit'
Print 'I am here2'
--SET IDENTITY_INSERT c365online_script1.dbo.tCompany ON
declare #cols2 varchar(max)
select #cols2 = (Select Stuff((Select ',' + QUOTENAME(C.COLUMN_NAME) [text()]
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, 1, '') As Columns
From INFORMATION_SCHEMA.TABLES As T
WHERE T.TABLE_NAME = #tablename)
DECLARE #sql NVARCHAR(MAX)
SET #sql = 'INSERT INTO ' + QUOTENAME(#Destination_Database_Name) + '.[dbo].' + QUOTENAME(#tablename) + ' (' + #cols2 + ') SELECT ' + #cols2 + ' FROM ' + QUOTENAME(#Source_Database_Name) + '.[dbo].' + QUOTENAME(#tablename) + '';
EXECUTE sp_Executesql #sql
Your need to change you #Sql Statement after you have used QOUTENAME function as it adds the square backets for you, you do not need to concatinate square barckets in your Sql statement.
Result
INSERT INTO [Trg_DataBaseName].[dbo].[TableName] ([Col1],[Col2],[Col3],[Col4],[Col5]) SELECT [Col1],[Col2],[Col3],[Col4],[Col5] FROM [Src_Database].[dbo].[TableName]
Related
I'm creating a pivot table but this error appears: Message 1087, level 15, state 2, line 6
Declare the table variable "#TABELLA_personale".
the #TABELLA_personale has been declared and works, so I don't understand what the problem is.
DECLARE #columns NVARCHAR(MAX), #sql NVARCHAR(MAX);
SET
#columns = N'';
SELECT
#columns += N', p.' + QUOTENAME((cast(IDUTENTE AS VARCHAR(MAX)) + ' ' + NOME + ' ' + COGNOME + ' ' + (ISNULL (LIVELLO, ''))))
FROM
(
SELECT
p.IDUTENTE,
p.NOME,
p.COGNOME,
p.LIVELLO
FROM
#TABELLA_personale AS p
INNER JOIN
#TABELLA_completa AS o
ON p.IDUTENTE = o.ID
GROUP BY
p.IDUTENTE,
P.NOME,
P.COGNOME,
P.LIVELLO
)
AS x;
SET
#sql = N'
SELECT
' + STUFF(#columns, 1, 2, '') + '
FROM
(
SELECT
p.NOME,
o.ORELAVORATE
FROM
#TABELLA_personale AS p
INNER JOIN
#TABELLA_completa AS o ONp.IDUTENTE = o.ID
)
AS j PIVOT ( MAX(ORELAVORARE) FOR NOME IN
(
'
+ STUFF(REPLACE(#columns, ', p.[', ',['), 1, 1, '') + ')) AS p;';
PRINT #sql;
EXEC sp_executesql #sql;
I would like to ask how can I add an apostrophe into a dynamic SQL. I need to return an SQL statement in one of the columns which has to have apostrophes in itself.
I have the following statement:
SET #SQL_String = N'INSERT INTO #ReturnTable
(
TableName,
ColName,
SQL_Statement,
Value
)
VALUES
(
''' + #TableName + ''',
''' + #ColName + ''',
''' +
'SELECT ' +
#ColName +
' FROM ' +
#TableSchema + '.' + #TableName +
' WHERE ' +
#ColName + ' = ' + CAST(#GuidArgument AS NVARCHAR(50)) + ';' +''',
(
SELECT
' + #ColName + '
FROM
' + #TableSchema + '.' + #TableName +
' WHERE '
+ #ColName + ' = ''' + CAST(#GuidArgument AS NVARCHAR(50)) +
'''))';
Executing with:
EXECUTE #RC = [dbo].[GetLocationOfGuidPre] 'F2CAB996-F00F-43B8-A67A-0000721A829D'
I need to put a whole first CAST into a pair of '.
I've tried:
Putting whole CAST statement into a separeted variable like: DECLARE #Test NVARCHAR(50);
SET #Test = CAST(#GuidArgument AS NVARCHAR(50));
SET #Test = 'CAST(#GuidArgument AS NVARCHAR(50))';
SET #Test = '''CAST(#GuidArgument AS NVARCHAR(50))''';
Addidng two more apostrophes:
' WHERE ' + #ColName + ' = ''' + CAST(#GuidArgument AS NVARCHAR(50)) + ''';'
Please use CHAR(39) instead of typing ' in your dynamic code directly.
Example:
declare #my_dynamic_sql nvarchar(max) = 'print char(39);';
exec(#my_dynamic_sql);
I am searching a query which generate html table. I found this query, but I can not understand what is use of such so many single quote used here and
why all code create in variable. I am new in sql please help me.
BEGIN
SET NOCOUNT ON;
IF #orderBy IS NULL
BEGIN
SET #orderBy = ''
END
SET #orderBy = REPLACE(#orderBy, '''', '''''');
DECLARE #realQuery NVARCHAR(MAX) = ' //this is variable which take all query as string
DECLARE #headerRow nvarchar(MAX);
DECLARE #cols nvarchar(MAX);
SELECT * INTO #dynSql FROM (' + #query + ') sub; -- how this temp table create
SELECT #cols = COALESCE(#cols + '', '''''''', '', '''') + ''['' + name + ''] AS ''''td''''''
FROM tempdb.sys.columns
WHERE object_id = object_id(''tempdb..#dynSql'')
ORDER BY column_id;
SET #cols = ''SET #html = CAST(( SELECT '' + #cols + '' FROM #dynSql ' + #orderBy + ' FOR XML PATH(''''tr''''), ELEMENTS XSINIL) AS nvarchar(max))''
EXEC sys.sp_executesql #cols, N''#html nvarchar(MAX) OUTPUT'', #html=#html OUTPUT
--in coalesce why so many '''' used
SELECT #headerRow = COALESCE(#headerRow + '''', '''') + ''<th>'' + name + ''</th>''
FROM tempdb.sys.columns
WHERE object_id = object_id(''tempdb..#dynSql'')
ORDER BY column_id;
SET #headerRow = ''<tr>'' + #headerRow + ''</tr>'';
SET #html = ''<table border="1">'' + #headerRow + #html + ''</table>'';
';
EXEC sys.sp_executesql #realQuery
,N'#html nvarchar(MAX) OUTPUT'
,#html = #html OUTPUT
END
Above query is working fine, but I can't understand it.
I want to replace special characters by normal characters in all columns dynamically for all columns of a table.But it works only for a column which is hardcoded
alter proc dbo.specialcharacterreplacer
#tblname varchar(1000),
#column_name varchar(1000)
as
begin
declare #Sql VARCHAR(MAX)
set #Sql = '
UPDATE ' + #tblname + ' SET ' + #column_name+ ' = REPLACE('+#column_name + ', ' + '''ó'''+ ', '+'''o'''+')
UPDATE ' + #tblname + ' SET ' + #column_name+ ' = REPLACE('+#column_name + ', ' + '''ò'''+ ', '+'''o'''+')
UPDATE ' + #tblname + ' SET ' + #column_name+ ' = REPLACE('+#column_name + ', ' + '''ö'''+ ', '+'''o'''+')
UPDATE ' + #tblname + ' SET ' + #column_name+ ' = REPLACE('+#column_name + ', ' + '''ð'''+ ', '+'''o'''+')
exec (#sql)
end
go
EXEC dbo.specialcharacterreplacer #tblname = 'dirtyyyysource', #column_name ='select *from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = '#tblname''
how to make columns dynamic?
This was the central code to get your update statement for all columns of a given table dynamically. Be aware of TABLE_SCHEMA and the column's type. You might use some additions in the WHERE part... (in my example you'd try to replace the INT column as well...)
And you might have a look here: https://stackoverflow.com/a/32048968/5089204
There you'll find one of my former answers to a similar question and shows an approach how to create a function which will replace several special characters in one go.
CREATE TABLE dbo.TestTable(ID INT,Test1 VARCHAR(100), Test2 VARCHAR(100));
GO
declare #tblname varchar(1000)='TestTable';
declare #tblschema varchar(1000)='dbo';
DECLARE #SqlCmd VARCHAR(MAX)= 'UPDATE ' + #tblname + ' SET ' +
(
STUFF(
(
SELECT ',' + COLUMN_NAME + ' = REPLACE(' + COLUMN_NAME + ', ' + '''ó'', ''o'''+')'+ CHAR(10) --might need to use CHAR(13)+CHAR(10)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA=#tblschema AND TABLE_NAME = #tblname
FOR XML PATH('')
),1,1,'') + ';'
);
SELECT #SqlCmd;
GO
DROP TABLE dbo.TestTable;
GO
The result:
UPDATE TestTable SET ID = REPLACE(ID, 'ó', 'o')
,Test1 = REPLACE(Test1, 'ó', 'o')
,Test2 = REPLACE(Test2, 'ó', 'o')
;
Is there is a way to generate a TVP from an existing table? I have tried this, https://dba.stackexchange.com/questions/12596/using-tables-as-table-valued-parameters-tvp but it's showing me syntax error?
-- you would pass these two in as parameters of course:
DECLARE
#TableName SYSNAME = N'LocationTable',
#TypeName SYSNAME = N'LocationTypeTable';
DECLARE #sql NVARCHAR(MAX) = N'';
SELECT #sql = #sql + N',' + CHAR(13) + CHAR(10) + CHAR(9)
+ QUOTENAME(c.name) + ' '
+ s.name + CASE WHEN LOWER(s.name) LIKE '%char' THEN
'(' + CONVERT(VARCHAR(12), (c.max_length/
(CASE LOWER(LEFT(s.name, 1)) WHEN N'n' THEN 2 ELSE 1 END)) + ')'
ELSE '' END
-- need much more conditionals here for other data types
FROM sys.columns AS c
INNER JOIN sys.types AS s
ON c.system_type_id = s.system_type_id
AND c.user_type_id = s.user_type_id
WHERE c.[object_id] = OBJECT_ID(#TableName);
SELECT #sql = N'CREATE TYPE ' + #TypeName
+ ' AS TABLE ' + CHAR(13) + CHAR(10) + (' + STUFF(#sql, 1, 1, '')
+ CHAR(13) + CHAR(10) + ');';
PRINT #sql;
-- EXEC sp_executesql #sql;
I have made modifications to your code above. This code executes but returns no values. What are you looking for exactly.
-- you would pass these two in as parameters of course:
DECLARE
#TableName SYSNAME
Set #TableName = N'LocationTable'
DECLARE
#TypeName SYSNAME
Set #TypeName = N'LocationTypeTable'
DECLARE #sql NVARCHAR(4000)
SET #sql= N'';
SELECT #sql = N',' + CHAR(13) + CHAR(10) + CHAR(9)
+ QUOTENAME(c.name) + ' '
+ s.name + CASE WHEN LOWER(s.name) LIKE '%char' THEN
-- '(' +
CONVERT(VARCHAR(12), (c.max_length/
(CASE LOWER(LEFT(s.name, 1)) WHEN N'n' THEN 2 ELSE 1 END)))
-- + ')'
ELSE '' END
-- need much more conditionals here for other data types
FROM sys.columns AS c
INNER JOIN sys.types AS s
ON c.system_type_id = s.system_type_id
AND c.user_type_id = s.user_type_id
WHERE c.[object_id] = OBJECT_ID(#TableName);
SELECT #sql = N'CREATE TYPE ' + #TypeName
+ ' AS TABLE ' + CHAR(13) + CHAR(10) + '(' + STUFF(#sql, 1, 1, '')
+ CHAR(13) + CHAR(10) + ');';
PRINT #sql;
-- EXEC sp_executesql #sql;