我可以通过SQL中的列数选择特定的列吗?
就像是

SELECT columns(0), columns(3), columns(5), columns(8) FROM TABLE


谢谢

最佳答案

您必须使用动态SQL来做到这一点:

DECLARE @strSQL AS nvarchar(MAX)
DECLARE @strColumnName AS nvarchar(255)
DECLARE @iCounter AS integer
DECLARE @curColumns AS CURSOR


SET @iCounter = 0
SET @strSQL = N'SELECT '

SET @curColumns = CURSOR FOR
(
    SELECT * FROM
    (
        SELECT TOP 99999
            COLUMN_NAME
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME = 'T_Markers'
        AND ORDINAL_POSITION < 4
        ORDER BY ORDINAL_POSITION ASC
    ) AS tempT
)

OPEN @curColumns
FETCH NEXT FROM @curColumns INTO @strColumnName
WHILE @@FETCH_STATUS = 0
BEGIN
    -- PRINT @strColumnName
    IF @iCounter = 0
        SET @strSQL = @strSQL + N'
     [' + @strColumnName + N'] '
    ELSE
        SET @strSQL = @strSQL + N'
    ,[' + @strColumnName + N'] '
    SET @iCounter = @iCounter + 1
FETCH NEXT FROM @curColumns INTO @strColumnName
END
CLOSE @curColumns
DEALLOCATE @curColumns

SET @strSQL = @strSQL + N'
FROM T_Markers
'

PRINT @strSQL

关于sql - sql server按编号选择列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17885667/

10-10 18:48