Solved

How to rotate rows into columns in a table using T-SQL

Posted on 2004-04-28
14
15,350 Views
Last Modified: 2009-07-29
I have a table named Table1 contains records like the following,

field name          data type          length
------------          -----------         --------
field1                 nvarchar           60
field2                 nvarchar           60
field3                 int                    4
field4                 datetime           8

How to create a new table using T-SQL with fields and types get from Table1 above.

Thanks in advance
0
Comment
Question by:ihenry
  • 5
  • 4
  • 3
  • +1
14 Comments
 
LVL 20

Author Comment

by:ihenry
Comment Utility
If possible without using cursor, please.
0
 
LVL 3

Expert Comment

by:Frostbyte_Zero
Comment Utility
TransactSQL does not have an option to transpose.

You could export the data to Excel and transpose each column into a row and then Import the data back. This could be done as long as you don't exceed the row or column limitations in Excel.

Other than that you must use a Cursor.
0
 
LVL 7

Expert Comment

by:ChrisFretwell
Comment Utility
You can do this without a cursor, but it can be messy.

What exactly do you want your end table to look like? Just to be clear.

0
 
LVL 20

Author Comment

by:ihenry
Comment Utility
I want to have a table structure something like this

create table NewTable
(
      field1      nvarchar(60),
      field2      nvarchar(60),
      field3      int,
      field4      datetime
)

But is has to be dynamically, since the number of records in Table1 could increase or decrease.
0
 
LVL 4

Accepted Solution

by:
BulZeyE earned 350 total points
Comment Utility

try:

create table #test (fieldname varchar(100), datatype varchar(100), length varchar(50))

insert into #test
(fieldname,datatype,length)
select 'field1',                 'nvarchar',           '60'
union all
select 'field2',                 'nvarchar',           '60'
union all
select 'field3',                 'int',                    '4'
union all
select 'field4',                 'datetime',           '8'

declare @SQLStatement      nvarchar(2000),
        @ColumnDefinition nvarchar(1000),
        @TableName        nvarchar(50)

set @TableName = 'ThisIsMyTableName'

select @SQLStatement = 'CREATE TABLE ' + @TableName + ' (**COLUMNDEFINITION**)'

select @ColumnDefinition = COALESCE(@ColumnDefinition + ',','')
       + FieldName
       + ' '
       + DataType
       + CASE
           WHEN DataType in ('VARCHAR','NVARCHAR','CHAR','NCHAR','FLOAT') -- THIS CAN BE ALTERED TO SUIT YOUR NEEDS
            AND Length IS NOT NULL THEN '(' + Length + ')'
           ELSE ''
         END
  FROM #TEST

drop table #test

SET @SQLStatement = REPLACE(@SQLStatement,'**COLUMNDEFINITION**',@ColumnDefinition)

EXEC(@SQLStatement)

0
 
LVL 7

Assisted Solution

by:ChrisFretwell
ChrisFretwell earned 75 total points
Comment Utility
Do you want to create a new table structure based on the values in the original table not populate a table with values in the original.

Thats not too hard. For this code, you will need to expand the case statement to format the data type correctly. I only used the ones in your example. But it should get you the idea. If you want to

declare @sql varchar(2000)

set @sql = 'create table newtable ('
select @sql = @sql  + char(13)+char(10)+ [field name] + ' ' + case when [data type] in ('int','datetime','smalldatetime') then [data type] else [data type] + '(' + convert(varchar(4),[length]) + ')' end + ','
from #table1

set @sql = @sql + ')'
set @sql = replace(@sql,',)',')')
print @sql
0
 
LVL 20

Author Comment

by:ihenry
Comment Utility
How messy the code would be look like? which one is better from performance benefit between using and not cursor?
I'll accept cursor if there's no other option.
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 7

Expert Comment

by:ChrisFretwell
Comment Utility
I printed teh statement, you'll want to exec it
0
 
LVL 7

Expert Comment

by:ChrisFretwell
Comment Utility
No need to a cursor, your question sounded a bit different from what you wanted, so I dont think its a problem.

In almost any case, you can write code without a cursor. Some may be easy to code, some not. But the performance with no cursor is almost always faster. (like my excessive use of almost?)
0
 
LVL 3

Expert Comment

by:Frostbyte_Zero
Comment Utility
If you are dealing with thousands of rows it will be messy.

But I have a solution. Use DTS ActiveX Scripting:

'**********************************************************************
'  Visual Basic ActiveX Script
'************************************************************************

Function Main()


      Dim ConnectString

      ' Build the Connection String
      ConnectString = "PROVIDER=SQLOLEDB"
      ConnectString = ConnectString & ";SERVER=yourserver"
      ConnectString = ConnectString & ";UID=yourid"
      ConnectString = ConnectString & ";PWD=yourpassword"
      ConnectString = ConnectString & ";DATABASE=yourdatabase"

      Dim con, cmd, rst
      Dim SQL

      SQL = "SELECT * FROM yourtable"

      Set con = CreateObject("ADODB.Connection")
      con.ConnectionString = ConnectString
      con.Open

      Set cmd = CreateObject("ADODB.Command")
      cmd.ActiveConnection = con
      cmd.CommandText = SQL
      cmd.CommandTimeout = 0

      Set rst = CreateObject("ADODB.Recordset")      
      rst.Open cmd      

      Dim DDL
                              
      If rst.BOF And rst.EOF Then

      Else


            DDL = "CREATE TABLE yournewtable("

            Do While Not rst.EOF                        

                  If rst(1) = "varchar" Or rst(1) = "nvarchar" or rst(1) = "char" Then

                  DDL = DDL & Trim(rst(0)) & " " & Trim(rst(1)) & "(" & Trim(rst(2)) & "), "

                  Else

                  DDL = DDL & Trim(rst(0)) & " " & Trim(rst(1)) & ", "

                  End If

                  rst.MoveNext

            Loop

            DDL = Mid( DDL, 1, Len( DDL) - 2)

            DDL = DDL & ")"

      End if

      ' Clean up variables.
      Set rst = Nothing
      Set cmd = Nothing
      Set con = Nothing

      MsgBox DDL

      Main = DTSTaskExecResult_Success
End Function

The DDL variable will contain the SQL to cxreate the table. Just pass it back to the command object to execute the command. Voila! Instant Table. I tested it and it works perfectly.
0
 
LVL 20

Author Comment

by:ihenry
Comment Utility
Hi all,

thanks for the code, i'm getting closer solving my problem. But it's leading me to one problem, though.

I'm able to execute this statement,
create table #temp1 (allow_Read int  default 0,allow_Add int  default 0,allow_Edit int  default 0,allow_Delete int  default 0 )
select * from #temp1
drop table #temp1


but i'm getting error "Invalid object name '#temp1'." when executing these lines:
declare @s nvarchar(4000)
set @s = 'create table #temp1 (allow_Read int  default 0,allow_Add int  default 0,allow_Edit int  default 0,allow_Delete int  default 0 )'
exec(@s)
select * from #temp1 --> at this line
drop table #temp1


If i change #temp1 to global temporary table ##temp1 it then works fine.
Any reason why to this problem?


0
 
LVL 3

Assisted Solution

by:Frostbyte_Zero
Frostbyte_Zero earned 75 total points
Comment Utility
#temp1 = Session Dependent Temporary Table
after exec(@s) the session is terminated
0
 
LVL 4

Expert Comment

by:BulZeyE
Comment Utility
Yes, the temp table that you are creating is being created but falls out of scope after the exec concludes. Then you try to reference it but it is already gone.

The code I posted is a valid T-SQL solution, have you tested it?
0
 
LVL 20

Author Comment

by:ihenry
Comment Utility
Great, Thanks for all the help.
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Performance is the key factor for any successful data integration project, knowing the type of transformation that you’re using is the first step on optimizing the SSIS flow performance, by utilizing the correct transformation or the design alternat…
Everyone has problem when going to load data into Data warehouse (EDW). They all need to confirm that data quality is good but they don't no how to proceed. Microsoft has provided new task within SSIS 2008 called "Data Profiler Task". It solve th…
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now