Wednesday, February 15, 2012

Dynamic SQL colunms into rows

Im trying to write a SQL script that will turn the rows from one table into colunms. I'm using the sp_excutesql porceure and it keeps coming back with an error.

The problem is that i cant seem to be able to use @.parameter as a name when i try to dynamically create a column. Its a dynamic sql problem but i cant seem to get around it.

This is the problem line -- SELECT @.SQL ='ALTER TABLE tblHM21 ADD @.ColName varchar(50)'

Create Table tblHM21 (uidHM21uniqueidentifier);-- loop through tests to get bring back names of the rows-- --declare @.rowCountintdeclare @.iintset @.i = 1set @.rowCount = (SELECTCount(intTestTableRow)FROM tblHSTests)while @.i <= @.rowCount
Begindeclare @.ColumnNamenvarchar(50)set @.columnName = (Select strTestNamefrom tblHStestswhere intTestTableRow = @.i)declare @.SQLnvarchar(500)declare @.paramsnvarchar(4000)SELECT @.SQL ='ALTER TABLE tblHM21 ADD @.ColName varchar(50)'SELECT @.params = N'@.ColName nvarchar(50)'EXECsp_executesql @.SQL, @.params, @.ColumnNameprint @.iprint @.ColumnNameset @.i = @.i+1Endselect *from tblHM21Drop Table tblHM21
hi

put

set@.SQL ='ALTER TABLE tblHM21 ADD @.ColName varchar(50)'
set @.params = N'@.ColName nvarchar(50)'
 
and before  execute print @.sql
no need to send parameter individually
u can add parameter within the sql statement 

|||

i tried that. I'll try agian theyere might be something i missed but i dont think so.

I have tired eveything and have figured out that it cant be done. Sanson

No comments:

Post a Comment