27
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'X' AND COLUMN_NAME = 'Y') 

IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Z' AND COLUMN_NAME = 'A')
BEGIN
    UPDATE [dbo].[X] 
        SET Y= (SELECT inst.[A] FROM [dbo].[Z] s WHERE s.[B] = [dbo].[x].[B]);
END    
    GO

我想结合 2 个 IF 条件并仅在它们都满足时才执行更新。如果存在的话,有什么方法可以让我加入俱乐部 2 吗?

4

3 回答 3

68

简单的:

IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'X' AND COLUMN_NAME = 'Y') 
AND EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Z' AND COLUMN_NAME = 'A')

BEGIN
    UPDATE [dbo].[X] 
        SET Y= (SELECT inst.[A] FROM [dbo].[Z] s WHERE s.[B] = [dbo].[x].[B]);
END    
GO
于 2013-07-01T23:02:43.563 回答
6

无需通过执行 SELECT * 来选择所有列。由于您正在检查是否存在行,因此请执行 SELECT 1 以加快查询速度。

IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
              WHERE TABLE_NAME = 'X' AND COLUMN_NAME = 'Y')

IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS 
          WHERE  TABLE_NAME = 'Z' AND COLUMN_NAME = 'A')

    BEGIN
        UPDATE [dbo].[X] 
            SET Y= (SELECT inst.[A] FROM [dbo].[Z] s WHERE s.[B] = [dbo].[x].[B]);
    END    
        GO
于 2013-07-02T02:40:47.147 回答
0

将标题和描述更改为空

UPDATE `li_categories`
  SET description = CASE
    WHEN description = '' THEN CONCAT('optional text ', title, ' optional text')
    ELSE description
    END
WHERE
 id
于 2015-11-24T14:26:39.480 回答