T-SQL /创建一个表,其列依赖于其他表的行

时间:2017-08-02 08:20:55

标签: sql-server tsql

我想根据另一个表的行值创建一个具有动态列数的新表。 例如,我有一个表(table1)有2列名为'VALUE'和'ISACTIVE'('ISACTIVE'列取值1如果我们需要将此值作为新表中的列考虑),我需要创建一个具有以下内容的新表: 新表的列数(和列名)=表1的值,其中Isactive = 1。

3 个答案:

答案 0 :(得分:0)

SELECT [attributeName] INTO [DatabaseName].[dbo].[NewTableName] 
FROM [DatabaseName].[dbo].[FromTableName] WHERE ISACTIVE=1

答案 1 :(得分:0)

我的第一个想法是根据您的条件在程序中动态创建它。阅读这个问题和答案,这将有所帮助。

enter image description here

原始示例

DECLARE @SQLString NVARCHAR(MAX)

SET @SQLString = N'CREATE TABLE <table_name> ('
        -- Conditons here
        SET @SQLString = @SQLString + '<column_name> <type>'

        -- End of conditions

    SET @SQLString = @SQLString + ')'

    EXEC (@SQLString)

答案 2 :(得分:0)

尝试以下。这是假设所有列都是整数。如果它是varchar,我们可以相应地修改。我们需要改变现有的表并添加一个名为textval的列,默认为&#39; 0&#39 ;这里

     drop table test
     create table test
    (
      value integer,
      isactive integer
    );
  alter table test add  textval nvarchar(max) default '0'
  insert into test (value,isactive) values (123,5);

   select * from test;

现在根据isactive的值更新新列。如果它是5,则新列将具有最多col5所有beign整数并使用它来创建新表

  begin 

   declare @i integer;
   set @i=1
   declare @isactive integer;
   declare @stmt nvarchar(max);
   declare @stmt2 nvarchar(max);
   declare @testval nvarchar(max);

   set @isactive= (select isactive from test)
   while (@i <=@isactive)
     begin
         declare @textval nvarchar(max);
         set @textval = (select textval from test)
        set @stmt= 'update test set textval = '''+ @textval +'col' +cast(@i 
        as varchar(100)) + ' ' + 'integer,'''

      execute sp_executesql @statement=@stmt
     set @i=@i+1;
    end 
  set @testval=(select left(replace(textval,'0col1','col1'),len(textval)-2) 
               from test)

   set @stmt2 ='create table tab1 ( ' + @testval + ' )';
   execute sp_executesql @statement=@stmt2;

  end