Hi all I have written the following Procedure to display the results as pivot as per the requirement
DECLARE #values AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
SELECT #values = STUFF(
(
SELECT DISTINCT ',[' + ColumnName + ']'
FROM xTable
FOR xml path ('')
),1,1,'')
SET #query = 'SELECT viewName1.*, pValues.Code, ' + #values + ' FROM
(
SELECT Column1,Column2, Column3
FROM viewname
) aliasName
PIVOT
(
MAX(value)
FOR ColumnName in (' + #values + ')
) pValues INNER JOIN viewName1 ON pValues.Code = viewname.Code'
EXEC(#query)
But when the value and column names are same in my xTable and viewName1 I am getting that error how can I resolve this. I tried with alas but I am not getting the expected result so can some one help me.
Sample is I am having a ColumnName as TopBrand in my table xTable, this can be a value in my viewName1 like for X Column TopBrand can be a value.
I think you need to have a separate list for FOR and IN clauses and the former should include the alias:
DECLARE #valuesFor AS NVARCHAR(MAX),
#valuesIn AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
SELECT #valuesFor = STUFF(
(
SELECT DISTINCT N',pValues.[' + ColumnName + ']'
FROM xTable
FOR xml path ('')
),1,1,'')
SELECT #valuesIn = STUFF(
(
SELECT DISTINCT N',[' + ColumnName + ']'
FROM xTable
FOR xml path ('')
),1,1,'')
SET #query = N'SELECT viewName1.*, pValues.Code, ' + #valuesFor + N' FROM
(
SELECT Column1,Column2, Column3
FROM viewname
) aliasName
PIVOT
(
MAX(value)
FOR ColumnName in (' + #valuesIn + N')
) pValues INNER JOIN viewName1 ON pValues.Code = viewname.Code'
EXEC(#query)
Related
I am working on an example to write dynamic sql to pivot the data in ssis expression builder.It fails to evaluate the expression. Below is the dynamic query:
DECLARE #Cols as NVARCHAR(MAX)
DECLARE #SQL as NVARCHAR(MAX)
SELECT #Cols = COALESCE(#Cols + ', ','') + QUOTENAME(Name)
FROM
(
SELECT DISTINCT Category
FROM Product
) As t1
SET #SQL = 'SELECT *
FROM
(
SELECT ProductID,
Category,
Quantity
FROM Product
) as PivotData
PIVOT
(
COUNT(Quantity)
FOR Category IN (" + #Cols + ")
) AS PivotResult'
I think your double quotes around + #Cols needs to be single quotes, see below.
DECLARE #Cols as NVARCHAR(MAX)
DECLARE #SQL as NVARCHAR(MAX)
SELECT #Cols = COALESCE(#Cols + ', ','') + QUOTENAME(Name)
FROM
(
SELECT DISTINCT Category
FROM Product
) As t1
SET #SQL = 'SELECT *
FROM
(
SELECT ProductID,
Category,
Quantity
FROM Product
) as PivotData
PIVOT
(
COUNT(Quantity)
FOR Category IN (' + #Cols + ')
) AS PivotResult'
I have the below code that works well but I don't want to continue typing in the dates daily.
My dates will always be the last 7 days (including today) - meaning that the table will be purged daily and the new data pull in daily.
select *
from
(
select EMP_ID, EMP_SHORT_NAME, SEG_CODE,
NOM_DATE
from sick_codes_Test$
) src
pivot
(
max(seg_code)
for nom_date in ([2018-07-14], [2018-07-15],[2018-07-16],[2018-07-17],[2018-07-18],
[2018-07-19], [2018-07-20])
) piv
So for "nom_date in" how can I make those dates the dates that will just be in the table?
I tried following along with the following link
https://www.mssqltips.com/sqlservertip/2783/script-to-create-dynamic-pivot-queries-in-sql-server/
But wasn't able to make it work
From following the above URL I came up with this code
DECLARE #columns NVARCHAR(MAX), #sql NVARCHAR(MAX);
SET #columns = N'';
SELECT #columns += N',' + QUOTENAME(NOM_DATE)
FROM sick_codes_Test$
SET #sql = N'
SELECT ' + STUFF(#columns, 1, 2, '') + '
FROM
(
SELECT EMP_ID, EMP_SHORT_NAME, SEG_CODE
from sick_codes_Test$
) AS j
PIVOT
(
max(seg_code) FOR nom_date IN ('
+ STUFF(REPLACE(#columns, ', [', ',['), 1, 1, '')
+ ')
) AS p;';
PRINT #sql;
EXEC sp_executesql #sql;
Any help would be greatly appreciated.
After more digging around I think I found a possible solution but after running the below I seeing the EMP_ID being duplicated.
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName= ISNULL(#ColumnName + ',','')
+ QUOTENAME(NOM_DATE)
FROM (SELECT DISTINCT NOM_DATE FROM sick_codes_Test$ ) AS NOM_DATE
order by NOM_DATE ASC
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery =
N'SELECT EMP_ID, EMP_SHORT_NAME, ' + #ColumnName + '
FROM sick_codes_Test$
PIVOT(MAX(SEG_CODE)
FOR NOM_DATE IN (' + #ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql #DynamicPivotQuery
After more modifications I finally found a solution that worked
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName= ISNULL(#ColumnName + ',','')
+ QUOTENAME(NOM_DATE)
FROM (SELECT DISTINCT NOM_DATE FROM sick_codes_Test$ ) AS NOM_DATE
order by NOM_DATE ASC
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery =
N'SELECT EMP_ID, EMP_SHORT_NAME, ' + #ColumnName + '
FROM (
SELECT DISTINCT EMP_ID,
EMP_SHORT_NAME,
SEG_CODE,
NOM_DATE
FROM sick_codes_Test$
)t
PIVOT(MAX(SEG_CODE)
FOR NOM_DATE IN (' + #ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql #DynamicPivotQuery
I want to run a query that shows me all columns from all tables in a database with the datatype varchar and a maximum length of 8000 characters.
This is my code so far.
DECLARE #tabs VARCHAR(MAX);
SET #tabs =
(
SELECT STUFF(( SELECT DISTINCT ',' + [TABLE_NAME]
FROM [DB-Test].INFORMATION_SCHEMA.COLUMNS
WHERE DATA_TYPE = 'VARCHAR' AND
CHARACTER_MAXIMUM_LENGTH = 8000
FOR XML PATH('')), 1, 1, '')
);
DECLARE #cols VARCHAR(MAX)
SET #cols =
(
SELECT STUFF(( SELECT DISTINCT ',' + [TABLE_NAME] + '.' + [COLUMN_NAME]
FROM [DB-Test].INFORMATION_SCHEMA.COLUMNS
WHERE DATA_TYPE = 'VARCHAR' AND
CHARACTER_MAXIMUM_LENGTH = 8000
FOR XML PATH('')), 1, 1, '')
);
DECLARE #query VARCHAR(MAX) = 'SELECT ' + #cols + ' FROM ' + #tabs
EXEC sp_sqlexec #query
When I run the query I get all the column names, but not the values in the columns. It's empty. No 'NULL'-values. As if #cols is interpreted as simple string maybe.
Why?
(When I read out #cols and #tabs they are correct.)
I guess there is one table available in your database which have column with VARCHAR datatype and 8000 length but that table don't have any records. Try by including only those column and table which have at least one record available.
You can try below. Check it and let me know if it works.
DECLARE #tabs VARCHAR(MAX) = ''
; WITH CTE AS
(
SELECT DISTINCT TA.NAME TABLENAME
, SUM(PA.ROWS) OVER (PARTITION BY TA.NAME ) NOOFROW
FROM SYS.TABLES TA
INNER JOIN SYS.PARTITIONS PA ON PA.OBJECT_ID = TA.OBJECT_ID
INNER JOIN SYS.SCHEMAS SC ON TA.SCHEMA_ID = SC.SCHEMA_ID
WHERE TA.IS_MS_SHIPPED = 0 AND PA.INDEX_ID IN (1,0)
), TABLENAME AS
(
SELECT ITBL.[TABLE_NAME]
FROM INFORMATION_SCHEMA.COLUMNS ITBL
WHERE ITBL.DATA_TYPE = 'VARCHAR' AND
ITBL.CHARACTER_MAXIMUM_LENGTH = 8000
AND EXISTS(SELECT 1 FROM CTE WHERE CTE.TABLENAME = ITBL.TABLE_NAME AND CTE.NOOFROW > 0) -- To check no of record available in table
)
SELECT #tabs = #tabs+ISNULL(','+TABLE_NAME, '')
FROM TABLENAME
DECLARE #cols VARCHAR(MAX) = '';
; WITH CTE AS
(
SELECT DISTINCT TA.NAME TABLENAME
, SUM(PA.ROWS) OVER (PARTITION BY TA.NAME ) NOOFROW
FROM SYS.TABLES TA
INNER JOIN SYS.PARTITIONS PA ON PA.OBJECT_ID = TA.OBJECT_ID
INNER JOIN SYS.SCHEMAS SC ON TA.SCHEMA_ID = SC.SCHEMA_ID
WHERE TA.IS_MS_SHIPPED = 0 AND PA.INDEX_ID IN (1,0)
), TABLENAME AS
(
SELECT ITBL.[TABLE_NAME], ITBL.[COLUMN_NAME]
FROM INFORMATION_SCHEMA.COLUMNS ITBL
WHERE ITBL.DATA_TYPE = 'VARCHAR' AND
ITBL.CHARACTER_MAXIMUM_LENGTH = 8000
AND EXISTS(SELECT 1 FROM CTE WHERE CTE.TABLENAME = ITBL.TABLE_NAME AND CTE.NOOFROW > 0) -- To check no of record available in table
)
SELECT #cols = #cols+ISNULL(','+[TABLE_NAME]+'.'+[COLUMN_NAME], '')
FROM TABLENAME
IF LEN(#cols) > 0 AND LEN(#tabs) > 0
BEGIN
DECLARE #query VARCHAR(MAX) = 'SELECT ' + STUFF(#cols,1,1,'') + ' FROM ' + STUFF(#tabs,1,1, '')
EXEC sp_sqlexec #query
END
ELSE
BEGIN
PRINT 'No Column available with data where it''s datatype is VARCHAR and length is 8000'
END
I have two tables named Emp and TrainingTable
Emp columns (EmpId(PK, int, not null), EmpName(nchar(10), null))
TrainingTable columns (EmpId(FK, int, null), TainingId(int, null), TainingName(nvarchar(50), not null))
Code:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME(TainingId)
from TrainingTable
group by TainingId
order by TainingId
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT EmpName,' + #cols + ' from
(
select Emp.EmpName, TainingName, TainingId
from TrainingTable INNER JOIN Emp ON TrainingTable.EmpId = Emp.EmpId
) x
pivot
(
max(TainingName)
for TainingId in (' + #cols + ')
) p '
execute(#query)
Now what I want to do is to rename the columns 1,2,3.. with Training1,Traning2,.. and so on..
the result table may change depending on data. columns may increase..
I tried almost every thing .. but not getting the correct way to achieve it.
Try this
You need to cast your column Using CAST()
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME('Training' + CAST(TainingId AS Varchar(50)))
from TrainingTable
group by TainingId
order by TainingId
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT EmpName,' + #cols + ' from
(
select Emp.EmpName,
TainingName,
col = ''Training'' + cast(TainingId as varchar(10))
from TrainingTable
INNER JOIN Emp ON TrainingTable.EmpId = Emp.EmpId
) x
pivot
(
max(TainingName)
for col in (' + #cols + ')
) p '
execute(#query)
Refer
I know how to find which table has that column name, by running:
select * From INFORMATION_SCHEMA.COLUMNS Where column_name = 'column value'
What i need now, is to find which tables have that certain column data.
It doesn't matter which column it belongs, I can find it, i just don't know which table to look at.
Joining these tables is not a solution, since there are a lot of tables.
Pls. let me know if you have ideas.
Thanks.
Will this do the job for you?
declare #data varchar(50)
,#sql varchar(max)
select #data = '%test%'
create table #Temp ([Table] varchar(200), [Column] varchar(200), [Data] varchar(max))
select #sql = isnull(#sql, '') + 'insert into #Temp select ''' + sys.tables.name + ''', ''' + sys.columns.name + ''', ' + sys.columns.name + ' from [' + sys.tables.name + '] where [' + sys.columns.name + '] like ''' + #data + ''';'
from sys.tables
inner join sys.columns
on sys.columns.object_id = sys.tables.object_id
exec(#sql)
select * from #Temp order by [Table], [Column]
drop table #Temp