Equivalent set base query for the cursor - sql

I have a stored procedure which uses cursor. I want to know any equivalent set base query for the cursor.
USE [T04_676]
GO
/****** Object: StoredProcedure [dbo].[proc_InsertAssessmentCast] Script Date: 3/16/2016 7:43:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Capgemini>
-- Create date: <12-Mar-2016>
-- Description: <This Stored procedure is used to create table 'assessment_cast' and fill data into it>
-- exec proc_InsertAssessmentCast
-- =============================================
CREATE PROCEDURE [dbo].[proc_InsertAssessmentCast]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #tmpTableNames TABLE
(
TableName varchar(250),
PatientID_ITM_ID INT,
date_ITM_ID INT,
KVSTableType INT,
Association_ITM_ID INT
)
DECLARE #tmpAssociatedColumn_ITM_ID TABLE
(
InitialTableMasterID INT
)
DECLARE #AssociatedColumn_ITM_ID INT
DECLARE #AssociatedColumn_ITM_ID_List VARCHAR(400)
DECLARE #TableName varchar(250)
DECLARE #PatientID_ITM_ID INT
DECLARE #date_ITM_ID INT
DECLARE #KVSTableType INT
DECLARE #Association_ITM_ID INT
DECLARE #SameRowID INT
DECLARE #T04PKID INT
DECLARE #T04CMID INT
DECLARE #T04Value VARCHAR(250)
DECLARE #sqlT04Value nvarchar(MAX)
DECLARE #tmpValue TABLE
(
Value varchar(250)
)
CREATE TABLE #tmpAssessmentRows
(
PrimaryKeyTableID INT,
ColumnID INT,
Value varchar(250)
)
DECLARE #sqlSameRowID NVARCHAR(250),#sqlT04_Value_Query NVARCHAR(MAX)
DECLARE #ColWithAliasTbl TABLE (colID int,colName varchar(50) )
DECLARE #PivotTBL VARCHAR(MAX)=''
DECLARE #ColID VARCHAR(MAX)
DECLARE #ChkPtntID VARCHAR(MAX)
DECLARE #ColName VARCHAR(MAX)
DECLARE #AllColID VARCHAR(MAX) = ''
DECLARE #AllColName VARCHAR(MAX) = ''
BEGIN TRY
IF EXISTS (SELECT name FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tmpAssesessment_Cast]') AND type in (N'U'))
BEGIN
DROP TABLE tmpAssesessment_Cast
END
IF EXISTS (SELECT name FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[assessment_cast]') AND type in (N'U'))
BEGIN
DROP TABLE assessment_cast
END
IF NOT EXISTS (SELECT name FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[InitialOriginalDataKVS]') AND name = N'ix_InitialOriginalDataKVS_SameRowID')
CREATE NONCLUSTERED INDEX [ix_InitialOriginalDataKVS_SameRowID] ON [dbo].[InitialOriginalDataKVS]
(
[InitialTableMasterID] ASC
)
INCLUDE ( [SameRowID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
--Insert Table names of tables having both columns: patientID and date
INSERT INTO #tmpTableNames
SELECT ITM1.TableName,ITM1.InitialTableMasterID,ITM2.InitialTableMasterID,ITM1.KVSTableType,0 AS Association_ITM_ID
FROM InitialTableMaster ITM1
INNER JOIN InitialTableMaster ITM2 ON ITM1.TableName=ITM2.TableName
WHERE ITM1.ColumnName ='patientID' AND ITM2.ColumnName ='date'
--Set Association for the column in table
UPDATE #tmpTableNames
SET Association_ITM_ID=Association
FROM InitialTableMaster ITM
INNER JOIN #tmpTableNames tmpTableNames ON tmpTableNames.TableName=ITM.TableName
WHERE Association <> 0 AND tmpTableNames.KVSTableType=1
--Do not consider tables with KVSTableType=1 having no Association
DELETE FROM #tmpTableNames
WHERE KVSTableType=1 AND Association_ITM_ID=0
SELECT TOP 1
#PatientID_ITM_ID=PatientID_ITM_ID,
#date_ITM_ID=date_ITM_ID,
#Association_ITM_ID=Association_ITM_ID
FROM #tmpTableNames
----Logic to get the associated columns ID values in list
INSERT INTO #tmpAssociatedColumn_ITM_ID
SELECT InitialTableMasterID
FROM InitialTableMaster
WHERE Association=#Association_ITM_ID and InitialTableMasterID <>#Association_ITM_ID
WHILE ((SELECT COUNT(1) FROM #tmpAssociatedColumn_ITM_ID)>0)
BEGIN
SELECT TOP 1 #AssociatedColumn_ITM_ID=InitialTableMasterID
FROM #tmpAssociatedColumn_ITM_ID
SET #AssociatedColumn_ITM_ID_List= ISNULL(#AssociatedColumn_ITM_ID_List,'') + '['+ CONVERT(NVARCHAR,#AssociatedColumn_ITM_ID) + '],'
DELETE FROM #tmpAssociatedColumn_ITM_ID
WHERE InitialTableMasterID=#AssociatedColumn_ITM_ID
END
SET #AssociatedColumn_ITM_ID_List=SUBSTRING(#AssociatedColumn_ITM_ID_List,0,LEN(#AssociatedColumn_ITM_ID_List))
print '1'
print #AssociatedColumn_ITM_ID_List
SET #sqlT04Value='
SELECT COALESCE('+ #AssociatedColumn_ITM_ID_List + ') as ''Value''
FROM [InitialOriginalDataKVS]
PIVOT(max(Value)
FOR InitialTableMasterID IN ('+ #AssociatedColumn_ITM_ID_List +')) AS PVTTable
WHERE SameRowID = '
--DECLARE GetSameRowIDs CURSOR STATIC LOCAL FOR
DECLARE GetSameRowIDs CURSOR FORWARD_ONLY READ_ONLY FAST_FORWARD FOR
SELECT sameRowID FROM InitialOriginalDataKVS
WHERE InitialTableMasterID=#PatientID_ITM_ID AND NewFlag=1
GROUP BY sameRowID
OPEN GetSameRowIDs
FETCH NEXT FROM GetSameRowIDs
INTO #SameRowID
WHILE (##FETCH_STATUS = 0) -- Inner cursor loop
BEGIN
SET #T04PKID=0
SELECT #T04PKID=PrimaryKeyTableID
FROM dbo.PrimaryKeyForPredicting
WHERE PatientID IN (SELECT value FROM dbo.InitialOriginalDataKVS
WHERE SameRowID=#SameRowID AND InitialTableMasterID=#PatientID_ITM_ID)
AND [date] IN (SELECT value FROM dbo.InitialOriginalDataKVS
WHERE SameRowID=#SameRowID AND InitialTableMasterID=#date_ITM_ID)
--Process only if the combination of patientID and date exists in 'PrimaryKeyForPredicting'
IF(ISNULL(#T04PKID,0)<> 0)
BEGIN
DELETE FROM #tmpValue
SET #T04Value=NULL
SET #sqlSameRowID=CONVERT(VARCHAR(50),#SameRowID)
SET #sqlT04_Value_Query=#sqlT04Value+#sqlSameRowID
INSERT INTO #tmpValue
EXEC sp_executesql #sqlT04_Value_Query
IF((SELECT COUNT(1) FROM #tmpValue)>0)
BEGIN
SELECT #T04Value=Value FROM #tmpValue
END
SELECT #T04CMID = ColumnID
FROM [dbo].[PrimaryKeyForModeling]
WHERE ColumnName IN (SELECT value FROM [InitialOriginalDataKVS]
WHERE SameRowID=#SameRowID AND InitialTableMasterID=#Association_ITM_ID)
IF(ISNULL(#T04CMID,0)<> 0)
BEGIN
INSERT INTO #tmpAssessmentRows
(PrimaryKeyTableID,ColumnID,Value)
VALUES(#T04PKID,#T04CMID,#T04Value)
END
END
FETCH NEXT FROM GetSameRowIDs
INTO #SameRowID
END
CLOSE GetSameRowIDs
DEALLOCATE GetSameRowIDs
SELECT PKP.PatientID,PKP.[Date],ColumnID,Value into tmpAssesessment_Cast
FROM #tmpAssessmentRows AR
INNER JOIN dbo.PrimaryKeyForPredicting PKP ON AR.PrimaryKeyTableID=PKP.PrimaryKeyTableID
order by PKP.PrimaryKeyTableID
-----------------------------
--Logic for assesment_cast table creation from the data in rows
------------------------------
INSERT INTO #ColWithAliasTbl
SELECT ColumnID,[ColumnName]
FROM [dbo].[PrimaryKeyForModeling]
WHERE ColumnID IN (SELECT Distinct ColumnID FROM tmpAssesessment_Cast)
While EXISTS (SELECT colID,colName FROM #ColWithAliasTbl)
Begin
SELECT #ColID='['+CONVERT(VARCHAR,min(colID))+'],' FROM #ColWithAliasTbl
SELECT #ColName='['+CONVERT(VARCHAR,colID)+'] AS '''+ colName+''',' FROM #ColWithAliasTbl WHERE colID = (SELECT min(colID) FROM #ColWithAliasTbl)
SET #AllColID = #AllColID+#ColID
SET #AllColName = #AllColName+#ColName
DELETE from #ColWithAliasTbl Where colID = (SELECT min(colID) FROM #ColWithAliasTbl)
End
print #AllColID
print LEN(#AllColID)
SET #AllColID = SUBSTRING(#AllColID, 1, LEN(#AllColID)-1)
print '2'
SET #AllColName = SUBSTRING(#AllColName, 1, LEN(#AllColName)-1)
print '3'
SET #PivotTBL = 'SELECT patientID, [date], '+#AllColName +
' into assessment_cast FROM (SELECT * FROM [dbo].[tmpAssesessment_Cast]) KVS
PIVOT (Max(Value) FOR [ColumnID] IN ('+#AllColID+') ) pvt order by 1'
EXEC(#PivotTBL)
--Drop temporary table
IF OBJECT_ID('dbo.tmpAssesessment_Cast', 'U') IS NOT NULL
DROP TABLE dbo.tmpAssesessment_Cast;
DROP TABLE #tmpAssessmentRows
--Return the assessment_cast table data
SELECT * FROM assessment_cast
END TRY
BEGIN CATCH
-- Raise an error with the details of the exception
DECLARE #ErrMsg nvarchar(4000), #ErrSeverity INT,#ErrorState INT
SELECT #ErrSeverity=ERROR_SEVERITY(),
#ErrMsg= ERROR_MESSAGE(),
#ErrorState=ERROR_STATE();
RAISERROR(#ErrMsg, #ErrSeverity, #ErrorState)
EXEC sp_addmessage 50005,#ErrSeverity,#ErrMsg,'us_english', 'with_log'
END CATCH
END
GO

Related

T-SQL function in Select to Only Return Columns with Values

I have a query that will return only columns with values. How do I add that to a function so I can use that with any query? Would it be a function in the where clause.
create table test1
(
s_no int not null,
name varchar(10) not null,
address varchar(10) null,
emailid varchar(100) null
)
insert into test1 (s_no, name)
values (1,'A'),(2,'B'),(3,'C')
declare #column_list varchar(8000),
#counter int
set #column_list = ''
set #counter = 0
while (Select max(colid) from syscolumns where id = object_id('test1') and isnullable= 0) > #counter
begin
select #counter = min(colid)
from syscolumns
where id = object_id('test1')
and isnullable = 0
and colid > #counter
select #column_list = #column_list + ',' + (Select name from syscolumns where id = object_id('test1') and isnullable= 0 and colid = #counter)
end
select #column_list = SUBSTRING(#column_list, 2, len(#column_list))
declare #sql varchar(8000)
select #sql = 'select ' + #column_list + ' from test1'
print #sql
exec (#sql)
SELECT * FROM [dbo].[test1]
I guess you could make a stored procedure where you provide the table name as parameter, and then build your query like you are doing already
create procedure ShowOnlyFilledColumns (#tablename varchar(100)) as
begin
set nocount on
declare #column_list varchar(8000),
#counter int
set #column_list = ''
set #counter = 0
while (Select max(colid) from syscolumns where id = object_id(#tablename) and isnullable= 0) > #counter
begin
select #counter = min(colid) from syscolumns where id = object_id(#tablename) and isnullable= 0 and colid > #counter
select #column_list = #column_list + ',' + (Select name from syscolumns where id = object_id(#tablename) and isnullable= 0 and colid = #counter)
end
select #column_list = SUBSTRING(#column_list,2,len(#column_list))
declare #sql varchar(8000)
select #sql = 'select ' + #column_list + ' from ' + #tablename
--print #sql
exec (#sql)
end
and use it like this
exec ShowOnlyFilledColumns 'test1'
See the complete example in this DBFiddle
EDIT: The OP asked how he can add joins on this
There are a few tricks to join with a stored procedure, for example in these answers
However, this won't work on this solution, because it requires to create a temp table to store the result of the procedure.
The trick looks like this
-- create a temporary table to store the results of the procedure
CREATE TABLE #Temp (
s_no int not null,
name varchar(10) not null,
address varchar(10) null,
emailid varchar(100) null
)
-- call the procedure and store the result in the temporary table
INSERT INTO #Temp
exec ShowOnlyFilledColumns 'test1'
-- now I can query the temp table, and join on it and write a where clause, and I can do whatever I want
select * from #Temp
Now, this won't work in this case, because the stored procedure can return different columns every time you run it, and to make the insert into #Temp exec ShowOnlyFilledColumns 'test1' work, the table #Temp must have the same number and type of columns as the procedure returns. And you just don't know that.

How to update unicode text to SQL Server from query window

I'm using the following code:
This is Update code:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[UpdateDataTable]
(#TABLEID BIGINT,
#QUERY NVARCHAR(MAX),
#DATAOBJECT NVARCHAR(MAX))
AS
BEGIN
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
BEGIN TRANSACTION TX1
-- DECLARATIONS
--DECLARE #DTABLE NVARCHAR(MAX) = 'DYNAMIC_Order_C905AE71028F4B0094B94EDAD0026CE2'
DECLARE #DTABLE NVARCHAR(MAX) = (SELECT DynamicTableId FROM TABLES WHERE Id=#TABLEID)
--DECLARE #QUERY NVARCHAR(MAX)='qty=4356'
--DECLARE #DATAOBJECT NVARCHAR(MAX)='{"product":"iPad 2018 pro", "amount":260000}'
-- BUILDING QUERY
DECLARE #QUERYSQL NVARCHAR(MAX) = 'SELECT Id AS TableId FROM '+#DTABLE+' WHERE '+#QUERY
-- RETRIEVING IDS OF UPDATING ROWS
DECLARE #UPDATING_IDS_TEMP TABLE(TableId BIGINT)
INSERT INTO #UPDATING_IDS_TEMP
EXEC sys.sp_executesql #QUERYSQL
DROP TABLE IF EXISTS #UPDATING_IDS
SELECT ROW_NUMBER() OVER (ORDER BY TableId)-1 AS Id, TableId
INTO #UPDATING_IDS
FROM #UPDATING_IDS_TEMP
-- UPDATING ROWS
DECLARE #INDEX BIGINT = 0
DECLARE #MAX BIGINT = (SELECT COUNT(*) FROM #UPDATING_IDS)
WHILE(#INDEX < #MAX)
BEGIN
--DECLARE #ROWID BIGINT = (SELECT TableId FROM #UPDATING_IDS WHERE Id=#INDEX)
DECLARE #ROWID BIGINT = 'N'''+ (SELECT TableId FROM #UPDATING_IDS WHERE Id=#INDEX) +''','
--SELECT #ROWID
EXEC FN_UpdateFieldByJson #DTABLE, #ROWID, #DATAOBJECT
SET #INDEX = #INDEX + 1
END
SELECT 'Completed'
COMMIT TRANSACTION T1
END
This is Insert Code
/****** Object: StoredProcedure [dbo].[InsertDataToTable] Script Date: 2/7/2020 1:57:07 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[InsertDataToTable](#tableId BIGINT, #data NVARCHAR(MAX))
AS
BEGIN
--DECLARE #tableId BIGINT = 10
--DECLARE #data NVARCHAR(MAX) = '{"artist":"usher","song name":"test songs"}'
DECLARE #dynamicTableId NVARCHAR(MAX) = (SELECT dynamicTableId FROM Tables WHERE Id=#tableId)
DECLARE #insertSql NVARCHAR(MAX)='INSERT INTO '+#dynamicTableId+'('
DECLARE #keyList NVARCHAR(MAX)=''
DECLARE #valueList NVARCHAR(MAX)=''
DROP TABLE IF EXISTS #FIELDS
SELECT ROW_NUMBER() OVER (ORDER BY [KEY])-1 AS Id,* INTO #FIELDS FROM OPENJSON(#data)
DECLARE #fieldCount BIGINT = (SELECT COUNT(*) FROM #FIELDS)
DECLARE #index BIGINT=0
WHILE ( #index < #fieldCount)
BEGIN
SET #keyList = #keyList+'['+(SELECT [KEY] FROM #FIELDS WHERE Id=#index)+'],'
-- ADDING WITHOUT QUOTES IF IT'S A NUMBER
IF ( (SELECT [TYPE] FROM #FIELDS WHERE Id=#index) = 2 )
BEGIN
SET #valueList = #valueList+''+dbo.ZenEncToChar((SELECT [VALUE] FROM #FIELDS WHERE Id=#index))+','
END
ELSE
BEGIN
SET #valueList = #valueList+'N'''+dbo.ZenEncToChar((SELECT [VALUE] FROM #FIELDS WHERE Id=#index))+''','
END
SET #index = #index+1
END
SET #keyList=SUBSTRING(#keyList,1, LEN(#keyList)-1)
SET #valueList=SUBSTRING(#valueList,1, LEN(#valueList)-1)
SET #insertSql = #insertSql + #keyList+') VALUES('+#valueList+')'
--SELECT #insertSql
EXEC sys.sp_executesql #insertSql
--SELECT ROW_NUMBER() OVER (ORDER BY COLUMN_NAME)-1 AS Id,COLUMN_NAME
--FROM INFORMATION_SCHEMA.COLUMNS
--WHERE TABLE_NAME = #dynamicTableId
END
User cannot insert/update ' symbol as table input in tables. So in here my insert table is working perfectly but update is not working. So please help me
How do I update unicode text from the SQL Server Management Studio query window?

Values not passed to dynamic query in sql server

Is it possible to print the Dynamic select statement after passing the parameters values.When i print the SELECT #SQL.It is giving only select statement without parameter values.In my below procedure the dynamic select statement not giving correct output after passing the parameters.But when i directly passing the the parameter values into the select statement it is giving correct output.In my below procedure splitting function is working fine.Else part in
if statement is not working properly.
CREATE TYPE TableVariable AS TABLE
(
id int identity(1,1),
field_ids INT,
value VARCHAR(MAX)
)
Alter PROCEDURE Testing
(
#TableVar TableVariable READONLY,
#Catalog_id INT
)
AS
Declare #maxPK INT
Declare #pk INT
Declare #fid INT
Declare #is_List SMALLINT
Declare #val VARCHAR(MAX)
Declare #field_Type VARCHAR(50)
Declare #Where VARCHAR(MAX)
Declare #SQL NVARCHAR(MAX);
Set #pk = 1
BEGIN
BEGIN TRY
SET NOCOUNT ON;
Select #maxPK = count(*) From #TableVar
SELECT #Catalog_id
Set #SQL = 'SELECT DISTINCT v1.entity_id from values v1 inner join listings l ON v1.entity_id = l.entity_id WHERE l.c_id=#Catalog_id'
While #pk <= #maxPK
BEGIN
SELECT #fid= field_ids FROM #TableVar where id=#pk;
SELECT #val= value FROM #TableVar where id=#pk;
SELECT #field_Type=type,#is_List=is_list FROM FIELD WHERE ID=#fid
IF (#is_List = 0)
BEGIN
SET #SQL += ' and exists (select 1 from values v'+convert(varchar(15),#pk+1)+' where v1.entity_id = v'+convert(varchar(15),#pk+1)+'.entity_id and v'+convert(varchar(15),#pk+1)+'.field_id=#fid and(value IN(SELECT val FROM spliting(#val,'',''))))'
SELECT #fid
END
else IF (#is_List = 1 OR #field_Type = 'xy')
BEGIN
SET #SQL += ' and exists (select 1 from values v'+convert(varchar(15),#pk+1)+' where v1.entity_id = v'+convert(varchar(15),#pk+1)+'.entity_id and v'+convert(varchar(15),#pk+1)+'.field_id=#fid and(value in(#val)))'
SELECT #fid
END
Select #pk = #pk + 1
END
EXECUTE SP_EXECUTESQL #SQL, N'#Catalog_id int,#fid int,#val varchar(max)',#Catalog_id=#Catalog_id,#fid=#fid,#val=#val
SELECT #SQL
END TRY
BEGIN CATCH
END CATCH
END
DECLARE #DepartmentTVP AS TableVariable;
insert into #DepartmentTVP values(1780,'Smooth As Silk Deep Moisture Shampoo,Smooth As Silk Deeper Moisture Conditioner')
--insert into #DepartmentTVP values(1780,'Smooth As Silk Deeper Moisture Conditioner')
insert into #DepartmentTVP values(1782,'037-05-1129')
insert into #DepartmentTVP values(2320,'["fairtrade","usda_organic","non_gmo_verified"]')
SELECT * FROM #DepartmentTVP
EXEC Testing #DepartmentTVP,583
Yes right before the statment:
EXECUTE SP_EXECUTESQL #SQL, N'#Catalog_id int,#fid int,#val varchar(max)',#Catalog_id=#Catalog_id,#fid=#fid,#val=#val
type:
print #SQL

SQL Server : drop constraint if exists

I have been struggling with this for about 2 hours now. I am trying to create a column to tables using a stored procedure. That said, I must check if that column exists, and if it does I must drop it.
The Issue is that I am not able to drop the constraint, I am getting an error:
invalid column name 'RowNumber'
Code:
DECLARE #tableName NVARCHAR(30)
DECLARE #newColumnName NVARCHAR(100)
DECLARE #newDefaultValue NVARCHAR(100)
DECLARE #newColumnType NVARCHAR(100)
DECLARE #constraintName NVARCHAR (30)
SET #tableName='TestTable'
SET #newDefaultValue = 'James'
SET #newColumnType ='NVARCHAR(100)'
SET #newColumnName = 'James'
CREATE TABLE #cons (constraintName NVARCHAR(100), RowNumber int)
INSERT INTO #cons(constraintName, RowNumber)
SELECT
t.*
FROM
(SELECT
name,
ROW_NUMBER() OVER(ORDER BY name) AS RowNumber
FROM
sys.objects
WHERE
type_desc LIKE '%CONSTRAINT'
AND name like '%JAMES%'
AND name like '%JAMES%') AS t
SELECT * FROM #cons
IF EXISTS(SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '[dbo].[TestTable]'
AND COLUMN_NAME = 'James')
BEGIN
DECLARE #i int
DECLARE #numberOfRows int
SET #i = 1
SET #numberOfRows = (SELECT COUNT(*) FROM #cons)
WHILE(#i <= #numberOfRows)
BEGIN
SET #constraintName = (SELECT constraintName
FROM #cons
WHERE RowNumber = #i)
DECLARE #dropStatement NVARCHAR(500)
SET #dropStatement = 'ALTER TABLE [dbo].[TestTable] DROP CONSTRAINT ' + #constraintName
EXEC(#dropStatement)
SET #i = #i + 1
END
ALTER TABLE [dbo].[TestTable]
DROP COLUMN [James]
END
--ALTER TABLE [dbo].[TestTable] ADD James NVARCHAR(50)
DROP TABLE #cons
How can I get this to drop the column?
ALTER TABLE
DROP CONSTRAINT #constraintname
Before the drop colum

Pivoting SQL Server 2005 for unknown number of rows

My table is a dynamic one. E.g.:
id SUBJECT
1 his
2 math
3 sci
4 opt
5 ENG
6 SOC
The number of rows is not limited. There could be a hundred. I want output like this:
ID 1 2 3 4 5 6
HIS MATH SCI OPT ENG SOC
I could use a pivot query, but I would have to know the number of columns. How can I do this without knowing the number of columns in advance?
i got an answer but it's very tricky
create a table for all your records
count the records
create a table with that much number of columns
create a comma separated variable for the table which has records
then split the comma separated variables into multiple columns
here is the code
DECLARE #HEADDESC NVARCHAR(150)
DROP TABLE #HEADS
CREATE TABLE #HEADS
(
ID INT IDENTITY
,HEADS NVARCHAR(150)
,NU INT
)
DECLARE #NO INT;
SET #NO = 0
DECLARE C1 CURSOR FOR (
SELECT HEADDESC
FROM GMC.FEEHEAD_MASTER
WHERE CODE = 'GF' AND HEADDESC <> '')
OPEN C1
FETCH NEXT FROM C1 INTO #HEADDESC
WHILE ##FETCH_STATUS = 0
BEGIN
PRINT #HEADDESC
SET #NO = #NO+1
INSERT INTO #HEADS(HEADS,NU)
VALUES(#HEADDESC,#NO)
FETCH NEXT FROM C1 INTO #HEADDESC
END
--SELECT * FROM #HEADS
CLOSE C1
DEALLOCATE C1
DECLARE #COLNO INT
SET #COLNO = (SELECT COUNT(*) FROM #HEADS)
DECLARE #COLUMNS VARCHAR(8000)
SELECT #COLUMNS = COALESCE(#COLUMNS +','+ CAST(HEADS AS VARCHAR) ,
CAST(HEADS AS VARCHAR))
FROM #HEADS
--GROUP BY HEADS
DECLARE #value NVARCHAR(100)
SET #value = ',1,STUDENTIDNO,STUDENTNAME,'
SET #COLUMNS = #VALUE+#COLUMNS
SET #COLNO = #COLNO+4
--SELECT #COLUMNS
DROP TABLE #HEADSCOMMA
CREATE TABLE #HEADSCOMMA(HEADS NVARCHAR(3000))
INSERT INTO #HEADSCOMMA VALUES (#COLUMNS)
DROP TABLE #TEMP
CREATE TABLE #TEMP(COL1 NVARCHAR(1000))
DECLARE #SQL NVARCHAR(MAX)
DECLARE #COL NVARCHAR(1000)
DECLARE #COL1 INT
DECLARE #COLNAME NVARCHAR(1000)
SET #COL1 = 2
SET #COL = 'COL'
PRINT #COL1
--SET #COLNAME = #COL +CAST(#COL1 AS NVARCHAR(10))
WHILE #COL1 < =#COLNO
BEGIN
SET #COLNAME = #COL +CAST(#COL1 AS NVARCHAR(100))
PRINT #COLNAME
SET #SQL = 'ALTER TABLE #TEMP ADD '+#COLNAME+' NVARCHAR(100)'
EXEC(#SQL)
SET #COL1= #COL1+1
END
--SELECT * FROM #HEADSCOMMA -- COMMA SEPERATED VALUES
DECLARE #S VARCHAR(8000), #DATA VARCHAR(8000)
--DROP TABLE #NORMALISEDTABLE
--CREATE TABLE #NORMALISEDTABLE (HEADS NVARCHAR(200))
SELECT #S=''
WHILE EXISTS (SELECT * FROM #HEADSCOMMA WHERE HEADS>#S)
BEGIN
SELECT #S=HEADS FROM #HEADSCOMMA WHERE HEADS>#S
PRINT #S
SELECT #DATA=''''+REPLACE(#S,',',''',''')+''''
PRINT #DATA
INSERT INTO #TEMP
EXEC('SELECT '+#DATA)
END
SELECT * FROM #temp
will give the records
Dynamic SQL is an option.