2017-08-02 68 views
0

我想创建一个具有动态列数的表,具体取决于其他表的行值。 例如,我有一个表(表1),它有2列名为'VALUE'和'ISACTIVE'(如果我们需要考虑这个值作为新表中的一列)'ISACTIVE'列取值1需要创建具有新表: 一些新表的列(和列名)=表1的值,其中Isactive = 1T-SQL /创建一个表,他的列取决于其他表的行

+0

什么应该是我们创建的列的数据类型? – Aparna

+0

您是否试图根据您的条件动态创建它(动态SQL查询)? – Cosmin

回答

0

尝试一下below.This是假设所有列是整数。我们可以进行相应的修改,如果它是VARCHAR。我们需要改变现有的表和添加一个名为textval栏默认为“0”这里

 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的新列w ^生病有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 <[email protected]) 
    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 @[email protected] 
    set @[email protected]+1; 
    end 
    set @testval=(select left(replace(textval,'0col1','col1'),len(textval)-2) 
       from test) 

    set @stmt2 ='create table tab1 (' + @testval + ')'; 
    execute sp_executesql @[email protected]; 

    end 
+0

thx mate这真的很有帮助。我还通过使用游标在字符串内部创建'update'语句找到了一种替代方法,并且它工作正常。你的方式虽然更先进!谢谢! – Marios88

+0

谢谢您...如果您认为该查询很有用,如果您可以投票支持,因为它可以被其他人使用 – Aparna

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

这会生成一个只有1列的新表(包含table1的值,其中isactive = 1)。我需要的是创建一个表,其中包含: 新表的列数=表1的行数,其中活动= 1 – Marios88

+0

您不能在列上应用条件,但如果您只想复制该表的结构表到选定列的新表,然后这就是你可以使用的内容:SELECT attributeName1,attributeName2 ... INTO [DatabaseName]。[dbo]。[NewTableName] FROM [DatabaseName]。[dbo]。[FromTableName] WHERE 1 = 2 – Rahul

0

我首先想到的是基于一个过程动态创建在你的条件下。阅读这个问题和答案,这将有所帮助。

T-SQL How to create tables dynamically in stored procedures?

原料例如

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) 
相关问题