I have a table in SQL Server 2005 with a variable number of columns, the first two being the only ones which are constant.
I’ve managed to get the number of columns in the table, so I would have what to count up to, but I don’t really know how to select a variable number of columns.
SELECT
DISTINCT
COUNT(*)
FROM
INFORMATION_SCHEMA.[COLUMNS]
WHERE
TABLE_NAME = 'SOME_TABLE'
AND
(COLUMN_NAME <> 'STATIC_COL1' AND COLUMN_NAME <> 'STATIC_COL2')
I’m guessing I need to use a while loop to get each column.
Any help would be appreciated.
Thanks.
Edit:
I ended up using @aF’s suggestion of dynamic SQL (see below)
DECLARE @CMD AS VARCHAR(MAX)
SET @CMD = 'SELECT '
DECLARE @COL AS VARCHAR(MAX)
DECLARE COLUMN_CURSOR CURSOR FOR
SELECT
COLUMN_NAME
FROM
INFORMATION_SCHEMA.[COLUMNS]
WHERE
TABLE_NAME = 'SOME_TABLE'
OPEN COLUMN_CURSOR
FETCH NEXT FROM COLUMN_CURSOR
INTO @COL
WHILE @@FETCH_STATUS = 0
BEGIN
IF @COL = 'STATIC_COL1'
BEGIN
SET @CMD = @CMD + @COL
END
FETCH NEXT FROM COLUMN_CURSOR
INTO @COL
SET @CMD = @CMD + ', CAST(' + @COL +' AS INT) AS ' + @COL
END
CLOSE COLUMN_CURSOR
DEALLOCATE COLUMN_CURSOR
SET @CMD = @CMD + ' FROM SOME_TABLE'
EXEC (@CMD)
One way to do it:
The following select gives you the list of columns:
With that, you can construct the intended query and use dynamic SQL to execute it.
Dynamic SQL is something like this:
In you case, you need to construct the
@cmdwith the columns from the first select.