2016-02-11 75 views
2

我有一個值,我得到這樣的:從先前添加的默認值列中選擇

select myValue from myTable where id=5 

我想一個nvarchar列添加到另一個表所在的默認值將是前一個。

但我不能看到如何該股前值在我加入柱腳本使用它:

IF NOT EXISTS(SELECT * FROM sys.columns WHERE [name] = N'NewColumn' AND [object_id] = OBJECT_ID(N'MySecondTable')) 
BEGIN 
    ALTER TABLE MySecondTable 
    ADD NewColumn nvarchar(250) NOT NULL DEFAULT 'my previous value'  
END 
GO 

預先感謝您的幫助!

回答

2

動態SQL救援:

DECLARE @defval NVARCHAR(500)=LEFT((SELECT myValue FROM myTable where id=5),250); 
SET @defval=REPLACE(@defval,N'''',N''''''); -- double single quotes for dynamic SQL statements 
DECLARE @stmt NVARCHAR(MAX)=N' 
    IF NOT EXISTS(SELECT * FROM sys.columns WHERE [name]=N''NewColumn'' AND [object_id]=OBJECT_ID(N''MySecondTable'')) 
    BEGIN 
    ALTER TABLE MySecondTable 
    ADD NewColumn nvarchar(250) NOT NULL DEFAULT N'''[email protected]+''' 
    END; 
'; 
EXECUTE sp_executesql @stmt; 
+0

@ user2443476注意,最好是** **名的限制,這樣,當你需要腳本修改後,你不必處理由SQL Server分配的隨機名稱。 –

1
DECLARE @default nvarchar(250) 
DECLARE @SQL nvarchar(max) 
SELECT @default = myValue from myTable WHERE id=5 

IF NOT EXISTS(SELECT * FROM sys.columns WHERE [name] = N'NewColumn' AND [object_id] = OBJECT_ID(N'MySecondTable')) 
BEGIN 
    SET @SQL = ' 
    ALTER TABLE MySecondTable 
    ADD NewColumn nvarchar(250) NOT NULL DEFAULT ''' + @default+'''' 
    EXEC sp_executesql @SQL  
END 
GO