如果条件合并语句

时间:2016-05-16 18:16:14

标签: sql sql-server

我有这个脚本:

DECLARE @TenantId INT = 1
IF EXISTS(SELECT 1 
            FROM [DB1].[Client1].information_schema.tables 
           WHERE table_type='BASE TABLE' 
             AND [TABLE_SCHEMA] = 'dbo'
             AND table_name='MyTable')
BEGIN

    MERGE info.[MyTable] AS t
    USING (
            SELECT [Id],
                   [Name]                  
              FROM [DB1].[Client1].dbo.MyTable
          ) s   
       ON (t.[Id] = s.[Id] AND t.[TenantId] = @TenantId)

    WHEN MATCHED THEN 
        UPDATE SET      
            t.[Name] = s.[Name]

    WHEN NOT MATCHED THEN 
        INSERT ([Id], [TenantId], [Name])
        VALUES (s.[Id], @TenantId, s.[Name]);

END  

为什么在USING内部的select中给出一个错误,如果表不存在?,当表不存在时我无法运行脚本。如果表存在就好了。

1 个答案:

答案 0 :(得分:0)

如果该表不存在则注释,则编译器将报错。试试这个:

 DECLARE @TenantId INT = 1
    IF EXISTS(SELECT 1 
                FROM [DB1].[Client1].information_schema.tables 
               WHERE table_type='BASE TABLE' 
                 AND [TABLE_SCHEMA] = 'dbo'
                 AND table_name='MyTable')

    BEGIN
    Declare @Sql Varchar(8000)
    Set @Sql =
   'MERGE info.[MyTable] AS t
    USING (
            SELECT [Id],
                   [Name]                  
              FROM [DB1].[Client1].dbo.MyTable
          ) s   
       ON (t.[Id] = s.[Id] AND t.[TenantId] = ' + Convert(Varchar(8000), @TenantId) + ')

    WHEN MATCHED THEN 
        UPDATE SET      
            t.[Name] = s.[Name]

    WHEN NOT MATCHED THEN 
        INSERT ([Id], [TenantId], [Name])
        VALUES (s.[Id], '+ Convert(Varchar(8000), @TenantId) + ', s.[Name]);
    Exec (@Sql)
END