2013-07-26 51 views
0

我需要在工作中編寫表修改腳本。而不是做一個簡單的「if exists then drop and create」,他們希望它檢查我添加的新列,然後只有在它們不存在的情況下才更改表。在將表添加到SQL Server之前檢查表列

有人可以幫我的腳本?假設一個簡單的表格,看起來像這樣目前:

CREATE TABLE myTable (

[ID] [int] NOT NULL, 
[FirstName] [varchar] (20) NOT NULL, 
[LastName] [varchar] (20) NOT NULL 

) 

..我想補充一個Address場,VARCHAR(50)假設,但只有當它沒有在架構已經存在。

回答

1

試試這個

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[myTable ]') AND type in (N'U')) 
BEGIN 
DROP TABLE [dbo].[myTable ] 
END 

SET ANSI_NULLS ON 
GO 

SET QUOTED_IDENTIFIER ON 
GO 

CREATE TABLE myTable (

[ID] [int] NOT NULL, 
[FirstName] [varchar] (20) NOT NULL, 
[LastName] [varchar] (20) NOT NULL, 
[Address] [varchar] (50) NOT NULL 
) 

OR

if not exists(select * from sys.columns 
      where Name = N'Address' and Object_ID = Object_ID(N'myTable'))  
begin 
    alter table myTable 
    add Address varchar(50) NOT NULL 
end 
GO 
+0

OP不想刪除表格。只需添加列如果它不存在 –

+0

看到我更新的答案 – Amit

4
IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_NAME = 'myTable' AND COLUMN_NAME = 'Address') 
BEGIN 

    ALTER TABLE [dbo].[myTable] ADD 
     [Address] varchar(50) NOT NULL 
END 
1
IF 'col_name' 
NOT IN 
    SELECT Name 
    FROM table_name.columns 
ALTER TABLE table_name 
ADD 'col_name' VARCHAR(65) NOT NULL 

這樣的事情?

編輯:我的朋友認爲這是更好的

IF NOT EXISTS 
    (SELECT Name 
    FROM table_name.columns 
    Where Name='target_column_name') 
ALTER TABLE table_name 
ADD 'target_column_name' VARCHAR(65) NOTNULL 
1

試試這個:

這裏使用它,你可以檢查多個欄目,讓你改變表...

DECLARE @query VARCHAR(MAX) 

IF EXISTS(SELECT * FROM sys.columns 
WHERE Name = N'Address' AND OBJECT_ID = OBJECT_ID(N'<TableName>')) 
BEGIN 
SET 
    @query = 'ALTER TABLE <TableName> ADD Address varchar(50) GO' 
END 

--You can give multiple If conditions, example: 
--IF EXISTS(SELECT * FROM sys.columns 
--WHERE Name = N'<SomeOtherColumn>' AND OBJECT_ID = OBJECT_ID(N'<TableName>')) 
--BEGIN 
--SET 
    [email protected] = @query + 'ALTER TABLE <TableName> ADD <SomeOtherColumn> varchar(50) GO' 
--END 

EXEC sp_Executesql @query 
相關問題