How can I dynamically create columns in SQL select statement - sql

I have 3 tables. Team, Option, OptionTeam.
The Team holds a TeamId and Name
Option holds OptionId, OptionGroup
OptionTeam holds TeamId, OptionId, OptionGroup
select a.TeamId, a.Name
(select count(*) from OptionTeam ot where ot.TeamId=a.TeamId and ot.OptionGroup=4) as Option1,
(select count(*) from OptionTeam ot where ot.TeamId=a.TeamId and ot.OptionGroup=5) as Option2,
(select count(*) from OptionTeam ot where ot.TeamId=a.TeamId and ot.OptionGroup=6) as Option3,
(select count(*) from OptionTeam ot where ot.TeamId=a.TeamId and ot.OptionGroup=11) as Option4
from Team a
I want to get a list of Teams, and extra columns indicating how many options of each group are connected to each Team. This is done by the above query, but I want to replace the 4,5,6,11 with values of OptionGroup from a table Option.
It has to be dynamic, because there might be a new OptionGroup in the future, and I want the stored procedure to be able to handle it.
Sample data:
Team
TeamId
1
2
3
Option
OptionId | OptionGroup
11 | 4
12 | 5
13 | 4
14 | 4
15 | 5
OptionTeam
TeamId | OptionId | OptionGroup
1 | 11 | 4
1 | 13 | 4
2 | 12 | 5
2 | 14 | 4
3 | 15 | 5
And the list I want to get is
TeamId | Group4 (OptionGroup=4) | Group5 (OptionGroup=5)
1 | 2 | 0
2 | 1 | 1
3 | 0 | 1

You'll need a dynamic pivot to do this. Here's the stored procedure:
CREATE PROC [dbo].[pivotsp]
#query AS NVARCHAR(MAX), -- The query, can also be the name of a table/view.
#on_rows AS NVARCHAR(MAX), -- The columns that will be regular rows.
#on_cols AS NVARCHAR(MAX), -- The columns that are to be pivoted.
#agg_func AS NVARCHAR(257) = N'SUM', -- Aggregate function.
#agg_col AS NVARCHAR(MAX), -- Column to aggregate.
#output AS NVARCHAR(257) = N'', -- Table for results
#debug AS bit = 0 -- 1 for debugging
AS
-- Example usage:
-- exec pivotsp
-- 'select * from vsaleshistory',
-- 'market,marketid,family,familyid,Forecaster,Forecasterid,product,productid',
-- 'month',
-- 'sum',
-- 'ku',
-- '##sales'
-- Input validation
IF #query IS NULL OR #on_rows IS NULL OR #on_cols IS NULL
OR #agg_func IS NULL OR #agg_col IS NULL
BEGIN
RAISERROR('Invalid input parameters.', 16, 1);
RETURN;
END
-- Additional input validation goes here (SQL Injection attempts, etc.)
BEGIN TRY
DECLARE
#sql AS NVARCHAR(MAX),
#cols AS NVARCHAR(MAX),
#newline AS NVARCHAR(2);
SET #newline = NCHAR(13) + NCHAR(10);
-- If input is a valid table or view
-- construct a SELECT statement against it
IF COALESCE(OBJECT_ID(#query, N'U'),
OBJECT_ID(#query, N'V')) IS NOT NULL
SET #query = N'SELECT * FROM ' + #query;
-- Make the query a derived table
SET #query = N'(' + #query + N') AS Query';
-- Handle * input in #agg_col
IF #agg_col = N'*'
SET #agg_col = N'1';
-- Construct column list
SET #sql =
N'SET #result = ' + #newline +
N' STUFF(' + #newline +
N' (SELECT N'','' + quotename( '
+ 'CAST(pivot_col AS sysname)' +
+ ') AS [text()]' + #newline +
N' FROM (SELECT DISTINCT('
+ #on_cols + N') AS pivot_col' + #newline +
N' FROM' + #query + N') AS DistinctCols' + #newline +
N' ORDER BY pivot_col' + #newline +
N' FOR XML PATH(''''))' + #newline +
N' ,1, 1, N'''');'
IF #debug = 1
PRINT #sql
EXEC sp_executesql
#stmt = #sql,
#params = N'#result AS NVARCHAR(MAX) OUTPUT',
#result = #cols OUTPUT;
IF #debug = 1
PRINT #cols
-- Create the PIVOT query
IF #output = N''
begin
SET #sql =
N'SELECT *' + #newline +
N'FROM (SELECT '
+ #on_rows
+ N', ' + #on_cols + N' AS pivot_col'
+ N', ' + #agg_col + N' AS agg_col' + #newline +
N' FROM ' + #query + N')' +
+ N' AS PivotInput' + #newline +
N' PIVOT(' + #agg_func + N'(agg_col)' + #newline +
N' FOR pivot_col IN(' + #cols + N')) AS PivotOutput;'
end
ELSE
begin
set #sql = 'IF EXISTS (SELECT * FROM tempdb.sys.objects WHERE ' +
'name = ''' + #output + ''' AND type = N''U'') DROP TABLE tempdb.' + #output
EXEC sp_executesql #sql;
SET #sql =
N'SELECT * INTO ' + #output + #newline +
N'FROM (SELECT '
+ #on_rows
+ N', ' + #on_cols + N' AS pivot_col'
+ N', ' + #agg_col + N' AS agg_col' + #newline +
N' FROM ' + #query + N')' +
+ N' AS PivotInput' + #newline +
N' PIVOT(' + #agg_func + N'(agg_col)' + #newline +
N' FOR pivot_col IN(' + #cols + N')) AS PivotOutput;'
end
IF #debug = 1
PRINT #sql
EXEC sp_executesql #sql;
END TRY
BEGIN CATCH
DECLARE
#error_message AS NVARCHAR(2047),
#error_severity AS INT,
#error_state AS INT;
SET #error_message = ERROR_MESSAGE();
SET #error_severity = ERROR_SEVERITY();
SET #error_state = ERROR_STATE();
RAISERROR(#error_message, #error_severity, #error_state);
RETURN;
END CATCH
With that, it's easy to pivot on a variable number of columns:
EXEC pivotsp
'SELECT TeamID, OptionGroup, OptionID AS Options FROM OptionTeam',
'Teamid', -- Row headers
'optiongroup', -- item to aggregate
'count', -- aggregation function
'optiongroup', -- Column header
'##temp' -- output table name
SELECT * FROM ##temp
Results:
Teamid 4 5
1 2 0
2 1 1
3 0 1

SELECT a.*, o.optionGroup, COUNT(*)
FROM team a
CROSS JOIN
option o
JOIN OptionTeam ot
ON ot.teamId = a.teamId
AND ot.optionGroup = o.optionGroup
WHERE o.OptionId = #id
GROUP BY
a.teamId, o.optionGroup

select teamID,
sum(case when optionGroup = 4 then 1 else 0 end) as optionGroup4,
sum(case when optionGroup = 5 then 1 else 0 end) as optionGroup5,
from optionteam
group by teamID
to add more optiongroups without changing the code, try grouping by that field:
select teamID,optionGroup,count(optionID) as optionCount
from optionteam
group by teamID,optionGroup

Related

Using pivot in SQL Server not returning desired output

I have two tables like this:
**tblTagDescription**
and **tblDataLog**
Now I want to show record of any specific group and in one there might be same group for multiple id in tbltagdescription. And id of tbltagdescription is foreign key for tblDataLog as TagDescID.
Here 'Group1' has 10 ID as from 1 to 10. and there might be multiple record for these ID (from 1 to 10) in tbldatalog. I want these ID from 1 to as columns. For this I used pivot:
DECLARE #COlsID NVARCHAR(MAX)
DECLARE #SQL NVARCHAR(MAX)
DECLARE #Group NVARCHAR(50) = 'Group1'
IF OBJECT_ID('tempdb..##MYTABLE') IS NOT NULL
DROP TABLE ##MYTABLE
SELECT
#COlsID = COALESCE(#ColsID + '],[','') + CONVERT(NVARCHAR(5), z.TagDescID)
FROM
(SELECT DISTINCT TOP 50 tblDataLog.TagDescID
FROM tblDataLog
INNER JOIN tblTagDescription ON tblDataLog.TagDescID = tblTagDescription.ID
ORDER BY tblDataLog.TagDescID) z
SET #COlsID='[' + #COlsID + ']'
SET #SQL='select [DATE],SHIFT, ' + #COlsID + ' into ##MYTABLE from ( select [Date], Value,
(CASE
WHEN ((DATEPART(hour,[DATE]))>6 and (DATEPART(hour,[DATE]))<14) THEN ''A''
WHEN ((DATEPART(hour,[DATE]))>=14 and (DATEPART(hour,[DATE]))<22) THEN ''B''
WHEN ((DATEPART(hour,[DATE]))>=22 or (DATEPART(hour,[DATE]))<6) THEN ''C''
END )AS SHIFT
from tblDataLog )d pivot(max(Value) for TagDescID in (' + #COlsID + ')) piv;'
EXEC (#SQL)
Now when I execute this statement, I get an error:
Invalid column name 'TagDescID'
but there is this column in tbldatalog. How to solve this query?
You need TagDescID column in subquery.
DECLARE #COlsID NVARCHAR(MAX) = ''
DECLARE #COlsAlias NVARCHAR(MAX) = ''
DECLARE #SQL NVARCHAR(MAX)
DECLARE #Group NVARCHAR(50) = 'Group1'
SELECT
#COlsID = #ColsID + ',' + z.TagDescID,
#COlsAlias = #COlsAlias + ',' + z.TagDescID + ' AS ' + z.ReportTag
FROM
(SELECT DISTINCT TOP 50 tblDataLog.TagDescID ID, QUOTENAME(CONVERT(NVARCHAR(5), tblDataLog.TagDescID )) TagDescID, QUOTENAME(tblTagDescription.ReportTag) ReportTag
FROM tblDataLog
INNER JOIN tblTagDescription ON tblDataLog.TagDescID = tblTagDescription.ID
ORDER BY tblDataLog.TagDescID
) z
SET #COlsID= STUFF(#COlsID,1,1,'')
SET #COlsAlias= STUFF(#COlsAlias,1,1,'')
SET #SQL='select [DATE],SHIFT, ' + #COlsAlias + ' into ##MYTABLE from ( select [Date], Value, TagDescID,
(CASE
WHEN ((DATEPART(hour,[DATE]))>6 and (DATEPART(hour,[DATE]))<14) THEN ''A''
WHEN ((DATEPART(hour,[DATE]))>=14 and (DATEPART(hour,[DATE]))<22) THEN ''B''
WHEN ((DATEPART(hour,[DATE]))>=22 or (DATEPART(hour,[DATE]))<6) THEN ''C''
END )AS SHIFT
from tblDataLog )d pivot(max(Value) for TagDescID in (' + #COlsID + ')) piv;'
EXEC (#SQL)

Dynamic pivot a 3 column table

I'm trying to use dynamic pivot to have a column containing dates to be the column names.
I want this table:
App Date Count
Excel 2018-05-01 1
Excel 2018-05-02 1
Excel 2018-05-03 2
Word 2018-05-02 3
Word 2018-05-07 5
Word 2018-05-12 2
Paint 2018-05-07 6
to look like this:
2018-05-01 2018-05-02 2018-05-03 2018-05-07 2018-05-12
Excel 1 1 2 0 0
Word 0 3 0 5 2
Paint 0 0 0 6 0
I can't use a normal pivot as I don't know how many or what the dates will actually be. Each app can have a different number of rows. This table isn't just a SELECT * FROM TABLE either, it's made up of subqueries and CTEs so is a little complicated to work with.
Any help is appreciated. Let me know if you need more information.
Using dynamic TSQL:
if OBJECT_ID('dbo.test') is null
create table dbo.test(App varchar(50), [Date] varchar(50), [Count] int)
truncate table dbo.test
insert into dbo.test values
('Excel', '2018-05-01', 1),
('Excel', '2018-05-02', 1),
('Excel', '2018-05-03', 2),
('Word ', '2018-05-02', 3),
('Word ', '2018-05-07', 5),
('Word ', '2018-05-12', 2),
('Paint', '2018-05-07', 6)
declare #dates nvarchar(max)='' --holds all the dates that will become column names
declare #dates_aliases nvarchar(max)='' --holds the headers without NULL values
declare #sql nvarchar(max)='' --contains the TSQL dinamically generated
select #dates = #dates + ', [' + CONVERT(char(10), [date],126)+ ']' from dbo.test
group by [date]
select #dates_aliases = #dates_aliases + ', isnull(['
+ CONVERT(char(10), [date],126)+ '], 0) as ['
+ CONVERT(char(10), [date],126)+ ']'
from dbo.test group by [date]
set #dates = RIGHT(#dates, len(#dates)-2)
set #dates_aliases = RIGHT(#dates_aliases, len(#dates_aliases)-2)
set #sql = #sql + ' select piv.[App], ' + #dates_aliases
set #sql = #sql + ' from '
set #sql = #sql + ' ( '
set #sql = #sql + ' select [App], [Date], [Count] '
set #sql = #sql + ' from dbo.test '
set #sql = #sql + ' ) src '
set #sql = #sql + ' pivot '
set #sql = #sql + ' ( '
set #sql = #sql + ' max([Count]) '
set #sql = #sql + ' for [Date] in ('+#dates+') '
set #sql = #sql + ' ) piv '
exec(#sql)
Results:
Try this:
SELECT A.*
INTO #TEMP
FROM
(
SELECT 'Excel' as app,'2018-05-01' as 'Date',1 as 'Count'
UNION ALL
SELECT 'Excel' as app,'2018-05-02' as 'Date',1 as 'Count'
UNION ALL
SELECT 'Excel' as app,'2018-05-03' as 'Date',2 as 'Count'
UNION ALL
SELECT 'Word' as app,'2018-05-02' as 'Date', 3 as 'Count'
UNION ALL
SELECT 'Word' as app,'2018-05-07' as 'Date', 5 as 'Count'
UNION ALL
SELECT 'Word' as app,'2018-05-12' as 'Date', 2 as 'Count'
UNION ALL
SELECT 'Paint' as app,'2018-05-07' as 'Date', 6 as 'Count'
) as A
ANSWER:
DECLARE #SQL VARCHAR(MAX)
DECLARE #Columns VARCHAR(MAX) = ''
DECLARE #Columns2 VARCHAR(MAX) = ''
SELECT #Columns = #Columns + '[' + a.[Column] + '], '
FROM
(SELECT DISTINCT [date] as [Column]
FROM #TEMP) as a
SELECT #Columns2 = #Columns2 + 'ISNULL([' + a.[Column] + '],0) as [' + a.[column] +'], '
FROM
(
SELECT DISTINCT [date] as [Column]
FROM #TEMP
) as a
SET #Columns2 = Left(#Columns2, Len(#Columns2) - 1)
SET #Columns = Left(#Columns, Len(#Columns) - 1)
SET #SQL = 'SELECT app, ' + #Columns2
+ ' FROM #TEMP PIVOT (Avg (Count) FOR Date IN ('
+ #Columns
+ ')) AS pt '
--PRINT #Columns
EXEC( #SQL )

SQL Server : creating a view from 2 tables

I have 2 tables, one with hoppers and the ingredients in them (Recorded once a day or when ingredients are changed)
Example:
Hoppers | Ingredients | Timestamp
--------+---------------+----------------------
Hop_1 | Ing_A | 8/22/2016 06:00:00
Hop_2 | Ing_B | 8/22/2016 06:00:00
etc...
And I have a second table that has totals used from each hopper recorded every hour
Example:
Name | Value | Timestamp
-------------------+----------+---------------------
Hop_1 Daily Total | 100 | 8/22/2016 11:00:00
Hop_1 Run Total | 30 | 8/22/2016 11:00:00
etc...
I would like to create a view that shows amount produced from each hopper and says the name.
Example:
Hop_1 Ingredient | Hop_1 Daily | Hop_1 Run | Timestamp
-----------------+-------------+-----------+-------------------
Ing_A | 100 | 30 | 8/22/2016 11:00:00
Sorry if it doesn't look good, I'm new at formatting
For the record I don't really think that structure is the best idea because it requires dynamic sql to pull it off with a couple of loops and lots of LEFT SELF JOINS. But here you go:
IF OBJECT_ID('tempdb..#Ingredients') IS NOT NULL
BEGIN
DROP TABLE #Ingredients
END
IF OBJECT_ID('tempdb..#Totals') IS NOT NULL
BEGIN
DROP TABLE #Totals
END
CREATE TABLE #Ingredients (Hoppers VARCHAR(25), Ingredeients VARCHAR(25), [Timestamp] DATETIME)
CREATE TABLE #Totals (Name VARCHAR(50), Value INT, [Timestamp] DATETIME)
INSERT INTO #Ingredients (Hoppers, Ingredeients, [Timestamp])
VALUES ('Hop_1','Ing_A','8/22/2016 06:00:00'),('Hop_2','Ing_B','8/22/2016 06:00:00'),('Hop_3','Ing_C','8/22/2016 06:00:00')
INSERT INTO #Totals (Name, Value, [Timestamp])
VALUES ('Hop_1 Daily Total',100,'8/22/2016 11:00:00'),('Hop_1 Run Total',30,'8/22/2016 11:00:00'),('Hop_1 Run Total',60,'8/22/2016 09:00:00')
,('Hop_2 Daily Total',500,'8/22/2016 11:00:00'),('Hop_2 Run Total',10,'8/22/2016 11:00:00'),('Hop_2 Run Total',5,'8/22/2016 10:00:00')
,('Hop_3 Daily Total',400,'8/22/2016 11:00:00'),('Hop_3 Run Total',85,'8/22/2016 11:00:00'),('Hop_3 Run Total',65,'8/22/2016 10:00:00')
DECLARE #HopperCount INT
SELECT #HopperCount = COUNT(DISTINCT i.Hoppers)
FROM
#Ingredients i
INNER JOIN #Totals t
ON t.Name LIKE i.Hoppers + '%'
DECLARE #I INT = 1
DECLARE #Sql NVARCHAR(MAX)
SET #Sql = '
;WITH cte AS (
SELECT
i.Hoppers
,i.Ingredeients
,Value
,t.[Timestamp]
,CASE WHEN t.Name LIKE ''%Daily%'' THEN 1 ELSE 0 END as IsDaily
,ROW_NUMBER() OVER (PARTITION BY i.Hoppers, t.name ORDER BY t.[Timestamp] DESC) as RunRowNum
,DENSE_RANK() OVER (PARTITION BY 1 ORDER BY i.Hoppers) as HooperNumber
FROM
#Ingredients i
INNER JOIN #Totals t
ON t.Name LIKE i.Hoppers + ''%''
AND i.[Timestamp] <= t.[Timestamp]
)
SELECT
c.Ingredeients AS [Hop_' + CAST(#I AS VARCHAR(10)) + ' Ingredient]
,SUM(CASE WHEN c.IsDaily = 1 THEN c.Value END) AS [Hop_' + CAST(#I AS VARCHAR(10)) + ' Daily]
,SUM(CASE WHEN c.IsDaily = 0 THEN c.Value END) AS [Hop_' + CAST(#I AS VARCHAR(10)) + ' Run]
,MAX(c.[Timestamp]) AS [Hop_' + CAST(#I AS VARCHAR(10)) + ' Timestamp] '
SET #I = 2
WHILE #I <= ISNULL(#HopperCount,0)
BEGIN
SET #Sql = #Sql + '
,c'+ CAST(#I AS VARCHAR(10)) + '.Ingredeients AS [Hop_' + CAST(#I AS VARCHAR(10)) + ' Ingredient]
,SUM(CASE WHEN c'+ CAST(#I AS VARCHAR(10)) + '.IsDaily = 1 THEN c' + CAST(#I AS VARCHAR(10)) + '.Value END) AS [Hop_' + CAST(#I AS VARCHAR(10)) + ' Daily]
,SUM(CASE WHEN c' + CAST(#I AS VARCHAR(10)) + '.IsDaily = 0 THEN c' + CAST(#I AS VARCHAR(10))+ '.Value END) AS [Hop_' + CAST(#I AS VARCHAR(10)) + ' Run]
,MAX(c' + CAST(#I AS VARCHAR(10)) + '.[Timestamp]) AS [Hop_' + CAST(#I AS VARCHAR(10)) + ' Timestamp] '
SET #I = #I + 1
END
SET #Sql = #Sql + '
FROM
cte c '
SET #I = 2
WHILE #I <= ISNULL(#HopperCount,0)
BEGIN
SET #Sql = #Sql + '
LEFT JOIN cte c' + CAST(#I AS VARCHAR(10)) + '
ON c.HooperNumber + ' + CAST(#I - 1 AS VARCHAR(10)) + ' = c' + CAST(#I AS VARCHAR(10)) + '.HooperNumber
AND c' + CAST(#I AS VARCHAR(10))+ '.RunRowNum = 1
AND c.IsDaily = c' + CAST(#I AS VARCHAR(10)) + '.IsDaily '
SET #I = #I + 1
END
SET #Sql = #Sql + '
WHERE
c.HooperNumber = 1
AND c.RunRowNum = 1
GROUP BY
c.Ingredeients
'
SET #I = 2
WHILE #I <= ISNULL(#HopperCount,0)
BEGIN
SET #Sql = #Sql + ',c' + CAST(#I AS VARCHAR(10)) + '.Ingredeients
'
SET #I = #I + 1
END
EXECUTE (#sql)
You could use a Pivot table for your need.
Here's a link : https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

Dynamically decide number of joins

I have two tables.
Table 1: Question_Master which contains the questions
id question
1 Q1
2 Q2
3 Q3
Table 2: Option Master Which contains the Options
id option
1 H
2 N
3 S
I want all the combinations of options for all the questions.
Something Like this
Q1 Q2 Q3
H H H
H H N
H H s
H N H
NOTE: There can be any number of records in both table.If it has 4 records in option_master than i want all combination for 4 records.
You can do it dynamically by using some string concatenation queries to build out the Select statement based on the Question_Master table values
DECLARE #SelectSQL VARCHAR(MAX),
#JoinSQL VARCHAR(MAX),
#OrderSQL VARCHAR(MAX)
SELECT #SelectSQL = COALESCE(#SelectSQL + ',', '')
+ QUOTENAME(question) + '.[option] as ' + QUOTENAME(question),
#JoinSQL = COALESCE(#JoinSQL + ' CROSS JOIN ', '')
+ 'Option_Master as ' + QUOTENAME(question),
#OrderSQL = COALESCE(#OrderSql + ',', '')
+ QUOTENAME(question) + '.[option]'
FROM Question_Master
ORDER BY question
DECLARE #Sql AS NVARCHAR(MAX) = N'SELECT ' + #SelectSQL + ' FROM ' + #JoinSQL + ' ORDER BY ' + #OrderSQL
EXECUTE sp_executesql #Sql;
using QUOTENAME will allow you to have questions that have spaces or some other characters in the value.
SQL Fiddle Example
You need to CROSS JOIN the Option_Master with itself. And then you need to cross join the result again with Option_Master. This has to be repeated for each question. I think this has to be done by dynamically creating the SQL statement. Try this example to get an idea:
declare #NumberOfQuestions int
set #NumberOfQuestions = (
select count(*)
from question_master
)
declare #sql varchar(max)
set #sql = 'select om1.opt '
declare #counter int
set #counter = 2
while #Counter <= #NumberOfQuestions
begin
set #sql = #sql + '
, om' + cast (#counter as varchar(1)) + '.opt '
set #counter = #counter + 1
end
set #sql = #sql + '
from option_master om1 '
set #counter = 2
while #Counter <= #NumberOfQuestions
begin
set #sql = #sql + '
cross join option_master om' + cast(#counter as varchar(1)) + ' '
set #counter = #counter + 1
end
set #sql = #sql + '
order by om1.opt '
set #counter = 2
while #Counter <= #NumberOfQuestions
begin
set #sql = #sql + '
, om' + cast(#counter as varchar(1)) + '.opt '
set #counter = #counter + 1
end
exec (#sql)
Albert

Convert Rows to Columns SQL 2008

I just want to transpose following table
RegionID Region RedionCode RegionSupervisor
1 Eastern E01 Mark
2 Western W01 Jim
3 Northern N01 Paul
4 Southern S01 David
to
Eastern Western Northern Southern
1 2 3 4
E01 W01 N01 S01
Mark Jim Paul David
I use SQL 2008. Any help would be really appreciated
cheers!
You can do this using the PIVOT and UNPIVOT tsql commands.
You can use PIVOT, but you will also need to incorporate dynamic SQL, as PIVOT by itself will only support situations where you know in advance the full set of columns in the resultant table. Pivots with Dynamic Columns in SQL Server 2005
Ok guys, finally I found a way of doing it but possibly not the more effective way. I could not find a solution with PIVOT yet
BEGIN
DECLARE #ColumnList varchar(200)
DECLARE #ColumnInList varchar(200)
DECLARE #TableName varchar(20)
DECLARE #TableScript varchar(2000)
SET #ColumnList = ''
SET #ColumnInList = ''
SELECT #ColumnInList += RTRIM(RegionDescription) + ',', #ColumnList += '[' + RTRIM(RegionDescription) + '] varchar(50) , '
FROM RegionSup
SET #ColumnList = LEFT(#ColumnList, LEN(#ColumnList) - 1)
SET #ColumnInList = LEFT(#ColumnInList, LEN(#ColumnInList) - 1)
SELECT #TableName = 'TEMP' + CONVERT(char(12),GETDATE(),14);
SELECT #TableName = REPLACE(#TableName,':','')
SET #TableScript = 'CREATE TABLE ' + #TableName + ' (' +
#ColumnList + ')'
EXECUTE (#TableScript)
--Column Values
DECLARE #RegionID varchar(30)
DECLARE #RegionSupervisor varchar(50)
DECLARE #RegionCode varchar(50)
--End Column Values
SET #RegionID = ''
SET #RegionSupervisor = ''
SET #RegionCode = ''
SELECT #RegionID += '''' + CONVERT(varchar(10),RegionID) + ''',',
#RegionSupervisor += '''' + RegionSupervisor + ''',',
#RegionCode += '''' + RegionCode + ''','
FROM RegionSup
SET #RegionID = LEFT(#RegionID,LEN(#RegionID) - 1)
SET #RegionSupervisor = LEFT(#RegionSupervisor,LEN(#RegionSupervisor) - 1)
SET #RegionCode = LEFT(#RegionCode,LEN(#RegionCode) - 1)
DECLARE #InsertStatement nvarchar(max)
SET #InsertStatement = ''
SET #InsertStatement = 'INSERT INTO ' + #TableName + '(' + #ColumnInList + ') VALUES ' +
'(' + #RegionID + '),' +
'(' + #RegionSupervisor + '),' +
'(' + #RegionCode + ')'
EXECUTE(#InsertStatement)
EXECUTE('SELECT * FROM ' + #TableName)
EXECUTE('DROP TABLE ' + #TableName)
END