如何遍历MS SQL表的内容并将行放入alter table中?

时间:2018-08-10 12:55:08

标签: sql-server database while-loop alter-table

我希望遍历表的内容(MS SQL),将名称收集在列中,并将其放入alter table循环中。

例如:

Bank names(column name) | Desc (column name)

Nationwide   | Example

HSBC         | Example

Halifax      | Example

ALTER TABLE banks

ADD (rows from bank table) varchar(255);

最终结果:

更改了另一个表格:

(Columns within new table \/)

Nationwide | HSBC | Halifax

1 个答案:

答案 0 :(得分:0)

您可以形成动态sql语句来执行此操作。

--Table to hold the banks while you work
CREATE TABLE #firsttable (Bank VARCHAR(20), Descr VARCHAR(20))
INSERT INTO #firsttable
(
    Bank
  , Descr
)
VALUES
('Nationwide', 'blah')
, ('HSBC','blah blah')
, ('Halifax', 'blah blah blah')

--The existing table you will be modifying
CREATE TABLE #existingtable (id INT)

--Variables
DECLARE @sql NVARCHAR(MAX)
DECLARE @currentbank VARCHAR(255)
DECLARE @banksleft INT

SELECT @banksleft = COUNT(1) FROM #firsttable;

--Loop through the banks
WHILE (@banksleft > 0)
    BEGIN
    SELECT @currentbank = bank FROM #firsttable;
    SELECT @sql = 'ALTER TABLE #existingtable ADD ' +  '[' + @currentbank  + '] varchar(255);' FROM #firsttable 

    --Run the alter statement
    EXEC sp_executesql @sql;

    --Get rid of the bank you have just added as a column
    DELETE
    FROM #firsttable WHERE Bank = @currentbank;
    --Reset the counter
    SELECT @banksleft = COUNT(1) FROM #firsttable;

    end

--To show the columns added to the table
SELECT * FROM #existingtable AS e;

--Cleanup
DROP TABLE #firsttable;
DROP TABLE #existingtable;