我如何 运行 通过 MS SQL table 的内容并将行放入 alter table?
How do I run through the contents of a MS SQL table and put the rows into a alter table?
我正在寻找 运行 通过 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);
最终结果:
改变了另一个 table:
(Columns within new table \/)
Nationwide | HSBC | Halifax
您可以形成动态 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;
我正在寻找 运行 通过 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);
最终结果:
改变了另一个 table:
(Columns within new table \/)
Nationwide | HSBC | Halifax
您可以形成动态 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;