web-dev-qa-db-fra.com

Comment utiliser la condition AND dans IF EXISTS en SQL?

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

Je souhaite combiner les 2 conditions IF et effectuer la mise à jour uniquement lorsque les deux sont satisfaites. Existe-t-il un moyen de lier une club à 2 SI EXISTE?

21
user811433

Simple: 

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
44
Vlad G.

Pas besoin de sélectionner toutes les colonnes en effectuant SELECT *. puisque vous vérifiez l'existence de lignes, faites SELECT 1 au lieu de rendre la requête plus rapide. 

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
6
Mudassir Hasan

Changer le titre et la description vide

UPDATE `li_categories`
  SET description = CASE
    WHEN description = '' THEN CONCAT('optional text ', title, ' optional text')
    ELSE description
    END
WHERE
 id
0
Limitless isa