how to concatenate n columns into one?

前端 未结 3 1434
余生分开走
余生分开走 2021-01-25 11:00

my goal is if I have this:

colmuns      c1 | c2 | c3 | c4 | c5 | n..
row1          a |  a |  a |  a |  a | 
row2          b |  b |  b |  b |  b |
rowN...
         


        
3条回答
  •  太阳男子
    2021-01-25 11:48

    You can simply use T-SQL's string concatenation operator '+'

    SELECT c1 + c2 + c3 + c4 + c5 + ...
    FROM myTable
    

    In case some of the columns may contain null values you can use the ISNULL() function, as in

    SELECT ISNULL(c1, '') + ISNULL(c2, 'x') + ...  -- note how you can substribute NULLs with any desired value
    FROM myTable
    

    You can dynamically create such SELECT statements by tapping into SQL Server metadata:

    SELECT COLUMN_NAME, *
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE table_name = 'myTable'
       AND DATA_TYPE IN ('char', 'varchar') -- can further filter out non desired colums
    order by ORDINAL_POSITION    -- and also pick a given order
    

    For example

    DECLARE @SqlStmt AS VARCHAR(8000)
    DECLARE @Ctr AS INT
    DECLARE @ColName AS VARCHAR(80)
    
    DECLARE colCursor CURSOR 
       FOR SELECT COLUMN_NAME
       FROM INFORMATION_SCHEMA.COLUMNS
       WHERE table_name = 'myTable'
          AND DATA_TYPE IN ('char', 'varchar')
      ORDER BY  ORDINAL_POSITION
      FOR READ ONLY;
    
    OPEN colCursor;
    
    SET @Ctr = 0
    SET @SqlStmt = 'SELECT '
    
    FETCH NEXT FROM colCursor INTO @colName;
    WHILE @@FETCH_STATUS = 0
    BEGIN
        IF @Ctr > 0
        BEGIN
            SET @SqlStmt = @SqlStmt + ' + '; -- w/o the spaces if size is a pb
        END
        SET @Ctr = @Ctr + 1;
        SET @SqlStmt = @SqlStmt + @ColName;   -- w/ ISNULL if needed...
    
        FETCH NEXT FROM colCursor INTO @colName;
    END;
    CLOSE colCursor
    DEALLOCATE colCursor
    
    SET @SqlStmt = @SqlStmt + ' FROM ' + 'myTable'
    -- Here to add to @SqlStmt (WHERE clause, other columns, other 
    -- tables/join whatever...
    
    PRINT @SqlStmt  -- OR EXEC() it ...
    

提交回复
热议问题