SQL PIVOT does not recognize a table - sql

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;

Related

Conversion failing when applying PIVOTED SCRIPT

i am having a data conversion issues when applying this un-pivoted script on my dynamic columns SSRS report .every time SSRS Report is executed the header columns are supposedly to change .
IF OBJECT_ID('tempdb..##Temp') IS NOT NULL
DROP TABLE ##Temp;
DECLARE #ObjectName VARCHAR(100) = '[AdventureWorks2016].[Sales].[SalesOrderHeader]' ,
#KeyColumn VARCHAR(100) = '[SalesOrderID]';
DECLARE #ColumnNames NVARCHAR(MAX)= '' ,
#Values NVARCHAR(MAX)= '' ,
#SQL NVARCHAR(MAX)= '';
SELECT #ColumnNames += ',
' + QUOTENAME([ShipDate]) ,
#Values += ',
' + QUOTENAME([ShipDate]) + ' = CONVERT(VARCHAR(100), '
+ QUOTENAME([ShipDate]) + ')'
FROM [AdventureWorks2016].[Sales].[SalesOrderHeader]
WHERE '[Sales].[SalesOrderHeader]' = #ObjectName
AND [ShipDate] <> #KeyColumn;
SET #SQL = N'Select * into ##Temp
FROM
(
SELECT ' + #KeyColumn + #Values + '
FROM ' + #ObjectName + '
) AS DRV
UNPIVOT
(
Value FOR ColumnName IN (' + STUFF(#ColumnNames, 1, 1, '') + ')
) AS UnPVT;';
EXEC sp_executesql #SQL;
SELECT *
FROM ##Temp

problem in executing dynamic query using pivot with syntax error Incorrect syntax near ' + '

I want to Create a query with dynamic query and in this query i use concat some cells , when use concat like 'N'subject:' + ' ' + ContentProductionTitle' i get syntax error
error : Incorrect syntax near ' + '.
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
SET #cols = STUFF((SELECT distinct ',' + QUOTENAME(c.KeyWordTitle)
FROM TBL_CU_ContentProduction_KeyWord c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT ' + #cols + ' from
(
select
isnull((select N'subject:' + ' ' + ContentProductionTitle
from Tbl_Cu_ContentProductionCalendar
where ContentProductionCalendarID = a.ActionSubjectId ),'')
+' ' +
isnull((select top 1 N'author:'+ p.FullName + ' ' from users.TblProfiles as p
where p.UserId= a.ActionUserID ),'') +' ' +
isnull((select top 1 N'edit bye:' + ' ' + p.FullName from users.TblProfiles as p
where p.UserId= a.CheckAgain ) ,'') as title
, a.ActionDateTo
, k.KeyWordTitle
from TBL_CU_ContentProduction_KeyWord as k
inner join Tbl_CU_ContentProduction as cp
on k.ContentGUID = cp.ContentGUID
inner join Tbl_Cu_ActionContentProduction as a
on a.ContentGUID = cp.ContentGUID
) x
pivot
(
max(ActionDateTo)
for KeyWordTitle in (' + #cols + ')
) p '
execute(#query)
you need to escape single quote inside your query string with '':
set #query = 'SELECT ' + #cols + ' from
(
select
isnull((select N''subject:'' + '' '' + ContentProductionTitle
from Tbl_Cu_ContentProductionCalendar
where ContentProductionCalendarID = a.ActionSubjectId ),'''')
+'' '' +
isnull((select top 1 N''author:''+ p.FullName + '' '' from users.TblProfiles as p
where p.UserId= a.ActionUserID ),'''') +'' '' +
isnull((select top 1 N''edit bye:'' + '' '' + p.FullName from users.TblProfiles as p
where p.UserId= a.CheckAgain ) ,'''') as title
, a.ActionDateTo
, k.KeyWordTitle
from TBL_CU_ContentProduction_KeyWord as k
inner join Tbl_CU_ContentProduction as cp
on k.ContentGUID = cp.ContentGUID
inner join Tbl_Cu_ActionContentProduction as a
on a.ContentGUID = cp.ContentGUID
) x
pivot
(
max(ActionDateTo)
for KeyWordTitle in (' + #cols + ')
) p '

Why EXEC sp_sqlexec #strSQL with EXECUTE (PRINT #strSQL) is different

I have this query:
CREATE PROCEDURE [dbo].[TraCuuBoTieuChi_Head]
#ChuoiLoai nvarchar(20),
#ChuoiXa nvarchar(MAX),
#ThangNam datetime
AS
DECLARE #strSQL nvarchar(MAX)
DECLARE #Str NVARCHAR(MAX)
DECLARE #Str2 NVARCHAR(MAX)
DECLARE #Str3 NVARCHAR(MAX)
DECLARE #Str4 NVARCHAR(MAX)
DECLARE #Str5 NVARCHAR(MAX)
DECLARE #Str6 NVARCHAR(MAX)
SET #Str = STUFF((SELECT ',' + (CASE WHEN items = 1 THEN 'SL_CuThe_Loai1 nvarchar(50)' WHEN items = 2 THEN 'SL_CuThe_Loai2 nvarchar(50)' ELSE 'SL_CuThe_Loai3 nvarchar(50)' END) FROM dbo.Split(#ChuoiLoai, ',') FOR XML PATH('')), 1, 1, '')
SET #Str2 = STUFF((SELECT ',' + (CASE WHEN items = 1 THEN 'SL_CuThe_Loai1' WHEN items = 2 THEN 'SL_CuThe_Loai2' ELSE 'SL_CuThe_Loai3' END) FROM dbo.Split(#ChuoiLoai, ',') FOR XML PATH('')), 1, 1, '')
SET #Str3 = STUFF((SELECT ',' + (CASE WHEN items = 1 THEN N'N''Giá trị mẫu 1''' WHEN items = 2 THEN N'N''Giá trị mẫu 2''' ELSE N'N''Giá trị mẫu 3''' END) FROM dbo.Split(#ChuoiLoai, ',') FOR XML PATH('')), 1, 1, '')
PRINT #Str3
SET #Str4 = STUFF((SELECT ',' + ('Xa' + items + ' nvarchar(100)') FROM dbo.Split(#ChuoiXa, ',') FOR XML PATH('')), 1, 1, '')
SET #Str5 = STUFF((SELECT ',' + ('Xa' + items ) FROM dbo.Split(#ChuoiXa, ',') FOR XML PATH('')), 1, 1, '')
SET #Str6 = STUFF((SELECT ',' + ((SELECT 'N''' + LocationName + '''' FROM Location WHERE LocationID = items)) FROM dbo.Split(#ChuoiXa, ',') FOR XML PATH('')), 1, 1, '')
PRINT #Str6
SET #strSQL = 'CREATE TABLE #tmp_paging_index (BulletCode nvarchar(30),TenTieuChi nvarchar(50),' + #Str + ',' + #Str4 + ')
INSERT INTO #tmp_paging_index (BulletCode,TenTieuChi,' + #Str2 + ',' + #Str5 + ')
SELECT N''BulletCode'',N''Tên tiêu chí'',' + #Str3 + ',' + #Str6 + '
SELECT * FROM #tmp_paging_index
DROP TABLE #tmp_paging_index'
PRINT #strSQL
EXEC sp_sqlexec #strSQL
When I run the procedure it outputs the following:
The Print section produces the following output:
*PRINT 1 : N'Giá trị mẫu 1',N'Giá trị mẫu 2',N'Giá trị mẫu 3'
PRINT 2: N'Xã Phú Hải',N'Xã Quảng Trung ',N'Xã Quảng Phong '
PRINT 3: CREATE TABLE #tmp_paging_index (BulletCode nvarchar(30),TenTieuChi nvarchar(MAX),SL_CuThe_Loai1 nvarchar(50),SL_CuThe_Loai2 nvarchar(50),SL_CuThe_Loai3 nvarchar(50),Xa14 nvarchar(100),Xa15 nvarchar(100),Xa16 nvarchar(100))
INSERT INTO #tmp_paging_index (BulletCode,TenTieuChi,SL_CuThe_Loai1,SL_CuThe_Loai2,SL_CuThe_Loai3,Xa14,Xa15,Xa16)
SELECT N'BulletCode',N'Tên tiêu chí',N'Giá trị mẫu 1',N'Giá trị mẫu 2',N'Giá trị mẫu 3',N'Xã Phú Hải',N'Xã Quảng Trung ',N'Xã Quảng Phong '
SELECT * FROM #tmp_paging_index
DROP TABLE #tmp_paging_index*
I run the print version and it came out different:
Now I have to do the same thing as running the print.
sp_sqlexec is from much earlier days. Not sure it is still supported on later version of SQL Server. You should use sp_executesql.
I found this thread on MSDN that mention sp_sqlexec does not support unicode. Probably that explain why you get different output
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/554d6373-8a22-4b10-8744-df13e5415f84/spexecutesql-vs-spsqlexec?forum=sqlgetstarted

Dynamically Generate TVP from an existing table?

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;

Incorrect syntax near ']'.?

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]