Select Into #Temp not working with a PIVOT - sql

I've got this dynamically created mess that essentially takes all fields in a table and compares two records against each other:
DECLARE #ID1 AS VarChar(3)
DECLARE #ID2 AS VarChar(3)
Set #ID1 = '42'
Set #ID2 = '600'
-- Where clause params
DECLARE #whereClauseParam VARCHAR(MAX) = '['+#ID1+'] <> ['+#ID2+']'
--***************************************--
--******** tblSQLAdminInventory ********--
--***************************************--
--Get the Fields required for the initial pivot
DECLARE #AIFields VARCHAR(MAX)= '';
DECLARE #AIFields2 VARCHAR(MAX)= '';
SELECT #AIFields+=QUOTENAME(t.name)+', '
FROM sys.columns AS t
WHERE t.object_id = OBJECT_ID('tblSQLAdminInventory')
AND t.name <> 'TransID'
--AND t.system_type_id = '56';
SELECT #AIFields2+='Convert(VarChar(250), '+QUOTENAME(t.name)+') AS '+ QUOTENAME(t.name) +', '
FROM sys.columns AS t
WHERE t.object_id = OBJECT_ID('tblSQLAdminInventory')
AND t.name <> 'TransID'
--AND t.system_type_id = '56';
--56 (Int)
--61 (DateTime)
--104 (Bit)
--167 (VarChar)
--231 (NVarChar)
-- Get the KeyId's with alias added
DECLARE #AIkeyIDs VARCHAR(MAX),
#AIkeyIDs1 VARCHAR(MAX);
SELECT #AIkeyIDs = COALESCE(#AIkeyIDs + ',','') + QUOTENAME(t.TransID) + ' AS [KeyID_' + CAST(t.TransID AS VARCHAR(10)) + ']',
#AIkeyIDs1 = COALESCE(#AIkeyIDs1 + ',','') + QUOTENAME(t.TransID)
FROM tblSQLAdminInventory AS t
WHERE TransID IN (#ID1, #ID2);
--Generate Dynamic SQL
DECLARE #AISQL2 VARCHAR(MAX)= 'SELECT Value AS FieldName, ';
SELECT #AISQL2+=#AIkeyIDs+'
FROM
(SELECT TransID, Value, FieldName
FROM
(SELECT TransID, '+SUBSTRING(#AIFields2, 1, LEN(#AIFields2)-1)+'
FROM tblSQLAdminInventory) p
UNPIVOT
(FieldName FOR Value IN
('+SUBSTRING(#AIFields, 1, LEN(#AIFields)-1)+')
)AS unpvt) AS SourceTable
PIVOT
(
MAX(FieldName)
FOR TransID IN ('+#AIkeyIDs1+')
) AS PivotTable
WHERE '+#whereClauseParam
EXECUTE(#AISQL2);
The problem is, it won't seem to let me put the results in a temp table. I tried using this code but it keeps telling me the #Temp1 object doesn't exist:
SELECT #AISQL2+=#AIkeyIDs+'
INTO #Temp1
FROM
(SELECT TransID, Value, FieldName
FROM
(SELECT TransID, '+SUBSTRING(#AIFields2, 1, LEN(#AIFields2)-1)+'
FROM tblSQLAdminInventory) p
UNPIVOT
(FieldName FOR Value IN
('+SUBSTRING(#AIFields, 1, LEN(#AIFields)-1)+')
)AS unpvt) AS SourceTable
PIVOT
(
MAX(FieldName)
FOR TransID IN ('+#AIkeyIDs1+')
) AS PivotTable
WHERE '+#whereClauseParam
What am I doing wrong?

You're using dynamic SQL. The EXECUTE statement starts a whole new scope and that temporary table isn't available in that scope.
There are several work-arounds, like using a permanent table that you clear out or using a global temporary table, but they all have their own pitfalls.

Related

Dynamic SQL stored procedure not populating temporary table

I am using a stored procedure with one parameter (#tablename) to generate a table of attributes about the table named via the parameter.
I call the stored procedure as follows
EXEC sp_Schema_Presentation #tablename = 'UserID'
And run the stored procedure (at the bottom of this post).
I have created a #DynamicSQL string in order to use my #tablename parameter. However, the SELECT statement, in which it's used, also creates the #TEMP table.
The rest of the query uses this #TEMP table so I DECLARE its structure at the top.
However, when I run the stored procedure, the #TEMP table is empty
If I hard code the #tablename, the query will work. Any ideas how I can fix this?
Thanks
CREATE TABLE #TEMP
(
SampleKey nvarchar(MAX),
SampleData nvarchar(MAX)
)
DECLARE #DynamicSQL NVARCHAR(MAX)
SET #DynamicSQL = N'SELECT B.*
INTO dbo.#TEMP
FROM (
SELECT * FROM ' + #Tablename + N' ORDER BY 1 DESC
OFFSET 1 ROWS
FETCH NEXT 1 ROWS ONLY
) A
CROSS APPLY (
SELECT [Key] AS SampleKey
,Value AS SampleData
FROM OpenJson( (SELECT A.* FOR JSON Path, Without_Array_Wrapper,INCLUDE_NULL_VALUES ) )
) B'
Full stored procedure in SQL Server 2016:
ALTER PROCEDURE [dbo].[sp_Schema_Presentation]
#TableName nvarchar(MAX)
AS
BEGIN
CREATE TABLE #TEMP
(
SampleKey nvarchar(MAX),
SampleData nvarchar(MAX)
)
DECLARE #DynamicSQL NVARCHAR(MAX)
SET #DynamicSQL = N'SELECT B.*
INTO dbo.#TEMP
FROM (
SELECT * FROM ' + #Tablename + N' ORDER BY 1 DESC
OFFSET 1 ROWS
FETCH NEXT 1 ROWS ONLY
) A
CROSS APPLY (
SELECT [Key] AS SampleKey
,Value AS SampleData
FROM OpenJson( (SELECT A.* FOR JSON Path, Without_Array_Wrapper,INCLUDE_NULL_VALUES ) )
) B'
DECLARE #Columns as NVARCHAR(MAX)
SELECT #Columns = COALESCE(#Columns + ', ','') + QUOTENAME(COLUMN_NAME)
FROM
(
SELECT COLUMN_NAME FROM PRESENTATION_PP.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N''' + #TableName + '''
) AS B
EXECUTE sp_executesql #DynamicSQL
SELECT a.COLUMN_NAME,
CASE WHEN a.COLUMN_NAME LIKE '%[_]_key' THEN a.COLUMN_NAME
ELSE REPLACE(a.COLUMN_NAME,'_',' ') END AS DISPLAY_NAME,
a.DATA_TYPE, COALESCE(a.CHARACTER_MAXIMUM_LENGTH, a.NUMERIC_PRECISION) AS SIZE,
CASE WHEN NUMERIC_SCALE IS NULL THEN 0
ELSE NUMERIC_SCALE END AS SCALE,
a.IS_NULLABLE AS NULLABLE,
CASE WHEN i.is_primary_key IS NOT NULL THEN 'YES'
ELSE 'NO' END AS PK,
#TEMP.SampleData
FROM PRESENTATION_PP.INFORMATION_SCHEMA.COLUMNS a
LEFT JOIN
sys.columns c ON a.COLUMN_NAME = c.name
LEFT JOIN
sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT JOIN
sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
LEFT JOIN
#TEMP ON a.COLUMN_NAME COLLATE SQL_Latin1_General_CP1_CI_AI = #TEMP.SampleKey COLLATE SQL_Latin1_General_CP1_CI_AI
WHERE TABLE_NAME = #TableName AND c.object_id = OBJECT_ID(#TableName)
SELECT * FROM #TEMP
DROP TABLE #TEMP
END
Create the #Temp table first, and then INSERT INTO not Select ... Into #Temp
CREATE TABLE #TEMP (SampleKey nvarchar(MAX), SampleData nvarchar(MAX))
DECLARE #DynamicSQL NVARCHAR(MAX)
SET #DynamicSQL = N'
Insert Into #Temp
SELECT B.*
FROM (
SELECT * FROM ' + #Tablename + N' ORDER BY 1 DESC
OFFSET 1 ROWS
FETCH NEXT 1 ROWS ONLY
) A
CROSS APPLY (
SELECT [Key] AS SampleKey
,Value AS SampleData
FROM OpenJson( (SELECT A.* FOR JSON Path, Without_Array_Wrapper,INCLUDE_NULL_VALUES ) )
) B
'
Exec(#DynamicSQL)
Select * from #Temp

how to select Columns using SQL which has data length greater than given length

I have a table with specific columns and rows. I would like to select columns which has data more than length 7.
For ex:
Table has columns
Name Address PhoneNumber
AAA AAAAAAAA 12345678
BBBBB BBBBBBB 47854
CCC FFFF 76643
Here columns 'Address ' and 'Phone Number' has data length more than 7. So it should display,
Address
PhoneNumber
as results. This is for a particular table. Here I do not know already that Address and PhoneNumber are the columns which have data greater than length 7. Only from the query result I will be able to find it.
SELECT <<all_columns>> from table where length(columns)>7 is my input requirement.
The LENGTH or LEN functions in 'Where' clause gives option to give only one specific column name
instead of LENGTH(COL_NAME) , I need option as where LENGTH(<> or something like LENGTH(*)) > 7 should be given as input.
How that can be achieved?
So HAVING is probably the clause youd want to use. Obviously, you can expand to include all columns and increase the having. see this:
SELECT
Name,
Address,
Phonenumber,
LEN(Address) AS AddyLength
FROM
yourTables
GROUP BY
Name,
Address,
Phonenumber,
HAVING
LEN(Address)>7
If you can live with the results in columns rather than rows:
select (case when max(length(name)) > 7 then 'Name;' else '' end) ||
(case when max(length(address)) > 7 then 'address;' else '' end) ||
(case when max(length(phone)) > 7 then 'phone;' else '' end)
from t;
As I read you need a dynamic sql for larger tables than your example (that should be part of your question)
I used unpivot to compare all lengths at once
DECLARE #TableName VARCHAR(100) = 'YourTableName'
DECLARE #MaxLen INT = 7
DECLARE #Definition
TABLE (
ColumnName VARCHAR(50)
)
INSERT #Definition
SELECT C.Name
FROM
sys.columns C
JOIN sys.tables T
ON C.object_id = T.object_id
WHERE t.name = #TableName
DECLARE #Columns VARCHAR(MAX) = ''
DECLARE #ColumnsWithCast VARCHAR(MAX) = ''
SET #Columns = STUFF(
(SELECT ',' + ColumnName
FROM #Definition
FOR XML PATH('')
),
1,
1,
'')
SET #ColumnsWithCast = STUFF(
(SELECT ',CAST(' + ColumnName + ' AS VARCHAR(MAX)) AS ' + ColumnName
FROM #Definition
FOR XML PATH('')
),
1,
1,
'')
DECLARE #SQL NVARCHAR(MAX) = N'
SELECT DISTINCT
Field
FROM (
SELECT
' + #ColumnsWithCast + '
FROM ' + #TableName + ' A
) p
UNPIVOT (
Value FOR Field IN (
' + #Columns + '
)
)AS unpvt
WHERE LEN(Value) > #MaxLen
'
DECLARE #ParamDefinition NVARCHAR(100) = N'#MaxLen INT'
EXEC sp_executesql #SQL, #ParamDefinition, #MaxLen = #MaxLen
It will generate this code with all the existing columns
SELECT DISTINCT
Field
FROM (
SELECT
CAST(Name AS VARCHAR(MAX)) AS Name,
CAST(Address AS VARCHAR(MAX)) AS Address,
CAST(PhoneNumber AS VARCHAR(MAX)) AS PhoneNumber,
FROM HIERARCHY A
) p
UNPIVOT (
Value FOR Field IN (
Name, Address, PhoneNumber
)
)AS unpvt
WHERE LEN(Value) > #MaxLen

How do I use loop to generate column names dynamically?

I have table sdata and it has 35 columns (id, name, TRx1, TRx2, TRx3, TRx4,..., TRx30, city, score, total)
I want to fetch data from the TRx1,...TRx30 columns.
Can I use loop here?
I did following code:
DECLARE #flag INT
DECLARE #sel varchar(255)
DECLARE #frm varchar(255)
SET #flag = 1;
SET #sel = 'select TRx';
SET #frm = ' from sdata';
exec(#sel +
(WHILE #flag <=5
#flag
SET #flag = #flag + 1)
+ #frm)
What wrong am I doing? And how can I resolve this?
If your table name is sdata, this code should work for you:
-- Grab the names of all the remaining columns
DECLARE #sql nvarchar(MAX);
DECLARE #columns nvarchar(MAX);
SELECT #columns = STUFF ( ( SELECT N'], [' + name
FROM sys.columns
WHERE object_id = (select top 1 object_id FROM sys.objects where name = 'sdata')
AND name LIKE 'TRx%' -- To limit which columns
ORDER BY column_id
FOR XML PATH('')), 1, 2, '') + ']';
PRINT #columns
SELECT #sql = 'SELECT ' + #columns + ' FROM sdata';
PRINT #sql;
EXEC (#sql);
Note I included PRINT statements so you could see what's going on. You might want to comment out the EXEC while testing.
This would be much easier to do by just copy/pasting the column names and changing them to be the correct one. However if you must do it this way, I do not advise using a loop at all. This method uses a tally table to generate the columns you want to select (in this example, columns 1 through 30, but that can be changed), then generates a dynamic SQL statement to execute against the SData table:
Declare #From Int = 1,
#To Int = 30,
#Sql NVarchar (Max)
Declare #Columns Table (Col Varchar (255))
;With Nums As
(
Select *
From (Values (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) As V(N)
), Tally As
(
Select Row_Number() Over (Order By (Select Null)) As N
From Nums A --10
Cross Join Nums B --100
Cross Join Nums C --1000
)
Insert #Columns
Select 'TRx' + Cast(N As Varchar)
From Tally
Where N Between #From And #To
;With Cols As
(
Select (
Select QuoteName(Col) + ',' As [text()]
From #Columns
For Xml Path ('')
) As Cols
)
Select #Sql = 'Select ' + Left(Cols, Len(Cols) - 1) + ' From SData'
From Cols
--Select #Sql
Execute (#Sql)
Note: The --Select #Sql section is there to preview the generated query before executing it.
You can select the column names like this:
SELECT column_name
FROM information_schema.columns
WHERE table_name = 'my name here'

Get top three most common values from every column in a table

I'm trying to write a query that will produce a very small sample of data from each column of a table, in which the sample is made up of the top 3 most common values. This particular problem is part of a bigger task, which is to write scripts that can characterize a database and its tables, its data integrity, and also quickly survey common values in the table on a per-column basis. Think of this as an automated "analysis" of a table.
On a single column basis, I do this already by simply calculating the frequency of values and then sorting by frequency. If I had a column called "color" and all colors were in it, and it just so happened that the color "blue" was in most rows, then the top 1 most frequently occurring value would be "blue". In SQL that is easy to calculate.
However, I'm not sure how I would do this over multiple columns.
Currently, when I do a calculation over all columns of a table, I perform the following type of query:
USE database;
DECLARE #t nvarchar(max)
SET #t = N'SELECT '
SELECT #t = #t + 'count(DISTINCT CAST(' + c.name + ' as varchar(max))) "' + c.name + '",'
FROM sys.columns c
WHERE c.object_id = object_id('table');
SET #t = SUBSTRING(#t, 1, LEN(#t) - 1) + ' FROM table;'
EXEC sp_executesql #t
However, its not entirely clear to me how I would do that here.
(Sidenote:columns that are of type text, ntext, and image, since those would cause errors while counting distinct values, but i'm less concerned about solving that)
But the problem of getting top three most frequent values per column has got me absolutely stumped.
Ideally, I'd like to end up with something like this:
Col1 Col2 Col3 Col4 Col5
---------------------------------------------------------------------
1,2,3 red,blue,green 29,17,0 c,d,j nevada,california,utah
I hacked this together, but it seems to work:
I cant help but think I should be using RANK().
USE <DB>;
DECLARE #query nvarchar(max)
DECLARE #column nvarchar(max)
DECLARE #table nvarchar(max)
DECLARE #i INT = 1
DECLARE #maxi INT = 10
DECLARE #target NVARCHAR(MAX) = <table>
declare #stage TABLE (i int IDENTITY(1,1), col nvarchar(max), tbl nvarchar(max))
declare #results table (ColumnName nvarchar(max), ColumnValue nvarchar(max), ColumnCount int, TableName NVARCHAR(MAX))
insert into #stage
select c.name, o.name
from sys.columns c
join sys.objects o on o.object_id=c.object_id and o.type = 'u'
and c.system_type_id IN (select system_type_id from sys.types where [name] not in ('text','ntext','image'))
and o.name like #target
SET #maxi = (select max(i) from #stage)
while #i <= #maxi
BEGIN
set #column = (select col from #stage where i = #i)
set #table = (select tbl from #stage where i = #i)
SET #query = N'SELECT ' +''''+#column+''''+' , '+ #column
SELECT #query = #query + ', COUNT( ' + #column + ' ) as count' + #column + ' , ''' + #table + ''' as tablename'
select #query = #query + ' from ' + #table + ' group by ' + #column
--Select #query
insert into #results
EXEC sp_executesql #query
SET #i = #i + 1
END
select * from #results
; with cte as (
select *, ROW_NUMBER() over (partition by Columnname order by ColumnCount desc) as rn from #results
)
select * from cte where rn <=3
Start with this SQL Statement builder, and modify it to suit your liking:
EDIT Added Order by Desc
With ColumnSet As
(
Select TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME
From INFORMATION_SCHEMA.COLUMNS
Where 1=1
And TABLE_NAME IN ('Table1')
And COLUMN_NAME IN ('Column1', 'Column2')
)
Select 'Select Top 3 ' + COLUMN_NAME + ', Count (*) NumInstances From ' + TABLE_SCHEMA + '.'+ TABLE_NAME + ' Group By ' + COLUMN_NAME + ' Order by Count (*) Desc'
From ColumnSet

Dynamic SQL to generate column names?

I have a query where I'm trying pivot row values into column names and currently I'm using SUM(Case...) As 'ColumnName' statements, like so:
SELECT
SKU1,
SUM(Case When Sku2=157 Then Quantity Else 0 End) As '157',
SUM(Case When Sku2=158 Then Quantity Else 0 End) As '158',
SUM(Case When Sku2=167 Then Quantity Else 0 End) As '167'
FROM
OrderDetailDeliveryReview
Group By
OrderShipToID,
DeliveryDate,
SKU1
The above query works great and gives me exactly what I need. However, I'm writing out the SUM(Case... statements by hand based on the results of the following query:
Select Distinct Sku2 From OrderDetailDeliveryReview
Is there a way, using T-SQL inside a stored procedure, that I can dynamically generate the SUM(Case... statements from the Select Distinct Sku2 From OrderDetailDeliveryReview query and then execute the resulting SQL code?
Having answered a lot of these over the years by generating dynamic pivot SQL from the metadata, have a look at these examples:
SQL Dynamic Pivot - how to order columns
SQL Server 2005 Pivot on Unknown Number of Columns
What SQL query or view will show "dynamic columns"
How do I Pivot on an XML column's attributes in T-SQL
How to apply the DRY principle to SQL Statements that Pivot Months
In your particular case (using the ANSI pivot instead of SQL Server 2005's PIVOT feature):
DECLARE #template AS varchar(max)
SET #template = 'SELECT
SKU1
{COLUMN_LIST}
FROM
OrderDetailDeliveryReview
Group By
OrderShipToID,
DeliveryDate,
SKU1
'
DECLARE #column_list AS varchar(max)
SELECT #column_list = COALESCE(#column_list, ',') + 'SUM(Case When Sku2=' + CONVERT(varchar, Sku2) + ' Then Quantity Else 0 End) As [' + CONVERT(varchar, Sku2) + '],'
FROM OrderDetailDeliveryReview
GROUP BY Sku2
ORDER BY Sku2
Set #column_list = Left(#column_list,Len(#column_list)-1)
SET #template = REPLACE(#template, '{COLUMN_LIST}', #column_list)
EXEC (#template)
I know that SO search engine is not perfect, but your question has been answered in SQL Server PIVOT Column Data.
Also see Creating cross tab queries and pivot tables in SQL.
Why do this using hard coded column names when you can pull all this dynamically from any table?
Using UNPIVOT and COALESCE, I can dynamically pull a list of columns from any table and associated column values for any record in a record listing and combine them in a list of column names with values by row. Here is the code. Just drop in your database and table name. The column/value table will be generated for you in SQL Server. Keep in mind, to get a shared column of values for the columns you want to convert to sql variant or text strings. But a great way to get a sample column list of values with matching column names and types with our while loops or cursors. Its pretty fast:
-- First get a list of all known columns in your database, dynamically...
DECLARE #COLUMNS nvarchar(max)
SELECT #COLUMNS =
CASE
WHEN A.DATA_TYPE = 'nvarchar' OR A.DATA_TYPE = 'ntext' THEN
COALESCE(#COLUMNS + ',','') + 'CAST(CONVERT(nvarchar(4000),['+A.[name]+']) AS sql_variant) AS ['+A.[name]+']'
WHEN A.DATA_TYPE = 'datetime' OR A.DATA_TYPE = 'smalldatetime' THEN
COALESCE(#COLUMNS + ',','') + 'CAST(CONVERT(nvarchar,['+A.[name]+'],101) AS sql_variant) AS ['+A.[name]+']'
ELSE
COALESCE(#COLUMNS + ',','') + 'CAST(['+A.[name]+'] AS sql_variant) AS ['+A.[name]+']'
END
FROM
(
SELECT
A.name,
C.DATA_TYPE
FROM YOURDATABASENAME.dbo.syscolumns A
INNER JOIN YOURDATABASENAME.dbo.sysobjects B ON B.id = A.id
LEFT JOIN
(
SELECT
COLUMN_NAME,
DATA_TYPE
FROM YOURDATABASENAME.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'YOURTABLENAME'
) C ON C.COLUMN_NAME = A.name
WHERE B.name = 'YOURTABLENAME'
AND C.DATA_TYPE <> 'timestamp'
) A
-- Test that the formatted columns list is returned...
--SELECT #COLUMNS
-- This gets a second string list of all known columns in your database, dynamically...
DECLARE #COLUMNS2 nvarchar(max)
SELECT #COLUMNS2 = COALESCE(#COLUMNS2 + ',','') + '['+A.[name]+']'
FROM
(
SELECT
A.name,
C.DATA_TYPE
FROM YOURDATABASENAME.dbo.syscolumns A
INNER JOIN YOURDATABASENAME.dbo.sysobjects B ON B.id = A.id
LEFT JOIN
(
SELECT
COLUMN_NAME,
DATA_TYPE
FROM YOURDATABASENAME.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'YOURTABLENAME'
) C ON C.COLUMN_NAME = A.name
WHERE B.name = 'YOURTABLENAME'
AND C.DATA_TYPE <> 'timestamp'
) A
-- Test that the formatted columns list is returned...
--SELECT #COLUMNS2
-- Now plug in the list of the dynamic columns list into an UNPIVOT to get a Column Name / Column Value list table...
DECLARE #sql nvarchar(max)
SET #sql =
'
SELECT
ColumnName,ColumnValue
FROM
(
SELECT
'+#COLUMNS+'
FROM YOURDATABASENAME.dbo.YOURTABLENAME
WHERE CHANGE_ID IN (SELECT ChangeId FROM YOURDATABASENAME.dbo.OperatorProcess WHERE OperatorProcessID = 3)
) AS SourceTable
UNPIVOT
(
ColumnValue FOR ColumnName IN ('+#COLUMNS2+')
) AS PivotTable
'
EXEC (#sql)
-- Darshankar Madhusudan i can do dynamic columnheading table easly...
--thanks
declare #incr int = 1,
#col int,
#str varchar(max),
#tblcrt varchar(max),
#insrt varchar(max),
set #tblcrt = 'DECLARE #Results table ('
set #str = ''
set #insrt = ''
select #col = max(column_id) From tempdb.sys.all_columns where object_id = object_id('tempdb.dbo.#aaa')
while #incr <= #col
BEGIN
SELECT #STR = #STR +case when #incr = 1 then '''' else ',''' end +rtrim(ltrim(NAME))+'''' FROM TEMPDB.SYS.ALL_COLUMNS WHERE OBJECT_ID = OBJECT_ID('TEMPDB.DBO.#AAA') and column_id = #incr
set #tblcrt = #tblcrt + case when #incr = 1 then '' else ',' end + 'Fld'+CAST(#incr as varchar(3)) +' varchar(50)'
set #insrt = #insrt + case when #incr = 1 then '' else ',' end + 'Fld'+CAST(#incr as varchar(3))
SET #INCR = #INCR + 1
END
set #tblcrt = #tblcrt + ')'
set #insrt = 'insert into #Results('+#insrt+') values (' + #STR +')'
set #tblcrt = #tblcrt+ ';' + #insrt + 'select * from #Results '
exec(#tblcrt)