I am writing a query to unpivot any table as required, based on it's first column and a selected row. And I am facing an issue in the dynamic query. The actual table has 77 columns with different data type that I tried to convert it to varchar and the values will always be of a particular row of a table.
example:
CREATE TABLE EXAMPLE (ROWDATA INT, CHARDATA VARCHAR(MAX), BIGINTCOLUMN BIGINT)
INSERT INTO EXAMPLE (ROWDATA INT, CHARDATA VARCHAR(MAX), BIGINTCOLUMN BIGINT)
VALUES (1, AB, 15698), (2, BD, 23467), (3, ABC, 42378)
- Now I want to do unpivot operation without putting columns so that I can use it for multiple purpose and there should only be 2 columns one is ColumnName that contains value
- "CHARDATA,BIGINTCOLUMN" other ColumnValue that contains value like "BD,23467" or "ABC,42378" '
CODE:
create table #ColumnName (Countno int identity(1,1), Column_Name varchar(max))
insert into #ColumnName (Column_Name) select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'EXAMPLE'
Create table #Converttype (Countno int identity(1,1), Converttype varchar(max))
insert into #Converttype (Converttype) select case when DATA_TYPE <> 'varchar' then 'Cast(' + COLUMN_NAME + ' as varchar) as '+ COLUMN_NAME else COLUMN_NAME end from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'EXAMPLE'
declare @CreateTable varchar(max) =(select Column_Name from #ColumnName where Countno = 1)
declare @Converttype varchar(max) = (select Converttype from #Converttype where Countno = 1)
declare @ColumnName varchar(max) = (select Column_Name from #ColumnName where Countno = 2)
declare @Iteration int = (select Count(COLUMN_NAME) from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'EXAMPLE')
declare @count int = 2
while @Count <= @Iteration
begin
--print @Count
set @CreateTable = @CreateTable+' varchar(max)' + ',' + (select Column_Name from #ColumnName where Countno = @count)
set @Converttype = @Converttype + ',' + (select Converttype from #Converttype where Countno = @count)
set @count = @count + 1
set @ColumnName = @ColumnName + ',' + isnull((select Column_Name from #ColumnName where Countno = @count),'')
end
declare @Unpivot nvarchar(max) = '
create table #temp (' + @CreateTable + ' varchar(max))
insert into #temp (ROWDATA,' + @ColumnName + ')
select ' + @Converttype + ' from EXAMPLE where ROWDATA = 2
select * from #temp
unpivot
(
ColumnValue
for ColumnName in (' + @ColumnName + ')
) AS Tablecheck'
Exec(@Unpivot)
- After debugging I found out that @Unpivot is not working specially when I used print @Unpivot it doesn't show me the the message from
select * from #tempto) as Tablecheck