SQL:BEGIN和END中的多个语句



我正在尝试向现有表中添加一个新列,该表将由一个唯一的Guid值填充。我正在尝试以下代码:

IF NOT EXISTS(select * from sys.columns 
        where Name = N'Product_GUID' and Object_ID = Object_ID(N'dbo.Product'))
BEGIN
    PRINT 'Creating new GUID column in dbo.Product table'
    ALTER TABLE dbo.Product
    ADD Product_GUID uniqueidentifier  NULL
    UPDATE dbo.Product
    SET Product_Guid=NEWID()
    ALTER TABLE dbo.Product 
    ALTER COLUMN Product_Guid uniqueidentifier NOT NULL
END 

这不会起作用,因为第二条语句无法识别新列名。我不能放GO或;不过,可能是因为我处于BEGIN/end块的中间。

解决这一困境的最佳方法是什么?

执行更新的语句必须在添加列之后编译。

通常这样做的方式是将语句包装在EXEC:中

EXEC(' UPDATE dbo.Product 
       SET Product_Guid = NEWID() 
      ALTER TABLE dbo.Product 
      ALTER COLUMN Product_Guid uniqueidentifier NOT NULL
') 

您似乎想要设置默认值,并使列不为null。如果你只将默认值设置为NEWID(),你会得到同样的效果

IF NOT EXISTS(select * from sys.columns 
        where Name = N'Product_GUID' and Object_ID = Object_ID(N'dbo.Product'))
BEGIN
    PRINT 'Creating new GUID column in dbo.Product table'
    ALTER TABLE dbo.Product
    ADD Product_GUID uniqueidentifier NOT NULL DEFAULT NEWID()
END 

如果之后需要删除约束,可以在alter语句中定义列之后创建DEFAULT约束,然后立即删除命名约束。如果不命名约束,则必须从sys.objects中获取名称,然后执行动态sql来删除它。

IF NOT EXISTS(select * from sys.columns 
        where Name = N'Product_GUID' and Object_ID = Object_ID(N'dbo.Product'))
BEGIN
    PRINT 'Creating new GUID column in dbo.Product table'
    ALTER TABLE dbo.Product
        ADD Product_GUID uniqueidentifier NOT NULL,
            CONSTRAINT Default_Product_GUID DEFAULT NEWID() FOR Product_GUID;
    ALTER TABLE dbo.Product DROP CONSTRAINT Default_Product_GUID
END 

您可以稍后更新该表,然后在另一个代码块中对其进行更改,类似于以下内容:

IF NOT EXISTS(select * from sys.columns 
        where Name = N'Product_GUID' and Object_ID = Object_ID(N'dbo.Product'))
BEGIN
    PRINT 'Creating new GUID column in dbo.Product table'
    ALTER TABLE dbo.Product
    ADD Product_GUID uniqueidentifier  NULL
END
GO
UPDATE dbo.Product
SET Product_Guid=NEWID()
Where Product_Guid is null
if @@ROWCOUNT <> 0
Begin
    ALTER TABLE dbo.Product 
    ALTER COLUMN Product_Guid uniqueidentifier NOT NULL
End

最新更新