ALTER TABLE SomeTableADD SomeCol Bit NULL --Or NOT NULL.CONSTRAINT D_SomeTable_SomeCol --When Omitted a Default-Constraint Name is autogenerated.DEFAULT (0)--Optional Default-Constraint.WITH VALUES --Add if Column is Nullable and you want the Default Value for Existing Records.
-- Add a column with a default DateTime-- to capture when each record is added.
ALTER TABLE myTableNameADD RecordAddedDate SMALLDATETIME NULL DEFAULT (GETDATE())GO
--------------------------------------------------------------------------- Drop COLUMN-- Name of Column: Column_EmployeeName-- Name of Table: table_Emplyee--------------------------------------------------------------------------IF EXISTS (SELECT 1FROM INFORMATION_SCHEMA.COLUMNSWHERE TABLE_NAME = 'table_Emplyee'AND COLUMN_NAME = 'Column_EmployeeName')BEGIN
IF EXISTS ( SELECT 1FROM sys.default_constraintsWHERE object_id = OBJECT_ID('[dbo].[DF_table_Emplyee_Column_EmployeeName]')AND parent_object_id = OBJECT_ID('[dbo].[table_Emplyee]'))BEGIN------ DROP Contraint
ALTER TABLE [dbo].[table_Emplyee] DROP CONSTRAINT [DF_table_Emplyee_Column_EmployeeName]PRINT '[DF_table_Emplyee_Column_EmployeeName] was dropped'END-- ----- DROP Column -----------------------------------------------------------------ALTER TABLE [dbo].table_EmplyeeDROP COLUMN Column_EmployeeNamePRINT 'Column Column_EmployeeName in images table was dropped'END
---------------------------------------------------------------------------- ADD COLUMN Column_EmployeeName IN table_Emplyee table--------------------------------------------------------------------------IF NOT EXISTS (SELECT 1FROM INFORMATION_SCHEMA.COLUMNSWHERE TABLE_NAME = 'table_Emplyee'AND COLUMN_NAME = 'Column_EmployeeName')BEGIN----- ADD Column & ContraintALTER TABLE dbo.table_EmplyeeADD Column_EmployeeName BIT NOT NULLCONSTRAINT [DF_table_Emplyee_Column_EmployeeName] DEFAULT (0)PRINT 'Column [DF_table_Emplyee_Column_EmployeeName] in table_Emplyee table was Added'PRINT 'Contraint [DF_table_Emplyee_Column_EmployeeName] was Added'END
GO
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNSWHERE TABLE_NAME ='TABLENAME' AND COLUMN_NAME = 'COLUMNNAME')BEGINALTER TABLE TABLENAME ADD COLUMNNAME Nvarchar(MAX) Not Null defaultEND
CREATE TABLE TestTable(FirstCol INT NOT NULL)GO-------------------------------- Option 1-------------------------------- Adding New ColumnALTER TABLE TestTableADD SecondCol INTGO-- Updating it with DefaultUPDATE TestTableSET SecondCol = 0GO-- AlterALTER TABLE TestTableALTER COLUMN SecondCol INT NOT NULLGO
好吧,我现在对我之前的答案进行了一些修改。我注意到没有一个答案提到IF NOT EXISTS。所以我将提供一个新的解决方案,因为我在改变表格时遇到了一些问题。
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.columns WHERE table_name = 'TaskSheet' AND column_name = 'IsBilledToClient')BEGINALTER TABLE dbo.TaskSheet ADDIsBilledToClient bit NOT NULL DEFAULT ((1))ENDGO