在MS SQL Server中通过查询动态添加列

时间:2015-07-07 09:36:53

标签: sql-server sql-server-2012

我在SQL Server 2012中有两个表。

表A

enter image description here

现在我想将TableB的TableA(Name)行添加为varchar(150)列。结果如下:

表B

enter image description here

我该怎么做?

3 个答案:

答案 0 :(得分:2)

您可以使用下面的代码动态添加列,基本上我正在构建动态ALTER TABLE语句以一次添加多个列。

 CREATE TABLE TableA (NAME Varchar(10), NameTYPE varchar(20))
    INSERT INTO TableA VALUES ('A','Excellent'),('B','Good'),('C','Poor')

    CREATE TABLE TableB(ID INT, FullName Varchar(20), Gender Char(2))

-- Check Table Column
    SELECT * FROM TableB


    DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX)

    select @cols = STUFF((SELECT  ',' + QUOTENAME(NAME)  +' Varchar(150)' 
                        from TableA
                        order by NAME
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)') 
            ,1,1,'')

    set @query = 'ALTER TABLE dbo.TableB Add ' + @cols 

    Exec (@Query)

-- Check Table Column
    SELECT * FROM TableB

答案 1 :(得分:0)

试试这个

declare @Rows int = 1
declare @colName nvarchar(150)
declare @Id int = 0
declare @MySql  nvarchar(max)


set @MySql = 'select  Id, FullName,Gendar, '

select  ROW_NUMBER() OVER(ORDER BY Name DESC) AS 'Id', Name  into #dt from TableA

WHILE @Rows>0
BEGIN

    SELECT top 1  @Id = Id, @colName =Name FROM #dt where Id >@Id

    set @Rows =@@RowCount
    if @Rows>0
    begin
        set @MySql = @MySql +   @colName     + ' ,'
    end

END
set @MySql = substring(@MySql,0,(len(@MySql)-1)) +' from TableA'
select @MySql

答案 2 :(得分:0)

你应该确定Name列不是dublicate

select  distinct Name  into #dtTemp from TableA
select  ROW_NUMBER() OVER(ORDER BY Name DESC) AS 'Id', Name  into #dt from #dtTemp