2017-08-02 66 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) 
相關問題