以下脚本出错

时间:2011-08-22 10:12:05

标签: sql-server tsql

我正在执行以下操作。我收到错误,无法找到错误是什么。可以帮我找到它。 a)检查DESTINATION数据库的可用性。如果不存在,请创建数据库并将表移动到数据库。 b)如果该表存在于DESTINATION数据库中,则该表不需要进程。

if db_id('Destination')is null
begin
Create database Destination
select * into TabDestination from [Source].[dbo].[TabSource]
end 
else
begin
use Destination
go
if('TabDestination' in (select name from sys.objects where type = 'u'))
insert into TabDestination select * from [Source].[dbo].[TabSource]
end

我正在犯错误

Msg 911, Level 16, State 1, Line 8
Database 'Destination' does not exist. Make sure that the name is entered correctly.
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near 'end'.

4 个答案:

答案 0 :(得分:3)

问题在于USE,来自文档:

  

USE在编译和执行时执行......

如果在编译时指定的数据库不存在,则查询将失败。您可以通过尝试运行以下查询来查看此内容:

IF 1 = 2
BEGIN
    USE NonexistantDatabase
END

尽管永远不会执行USE语句,但此查询失败。

您应该更改查询以使用数据库限定名称,例如:

INSERT INTO Destination.dbo.Table SELECT * FROM Source.dbo.Table

答案 1 :(得分:1)

这里几乎没有问题:

  • Create database Destination之后,您需要在执行select * into TabDestination...之前使用该数据库,因为您将在其他数据库中创建TabDestination
  • Go块中间的begin...end无效。
  • 要为TabDesitination的插入指定数据库,最好使用表格的完全限定名称,而不是调用Use,例如Insert Destiation.dbo.TabDestination...
  • 您需要使用If Exists (select...作为第二个if语句。
  • 因为脚本编译时你的数据库可能不存在,所以需要动态执行很多sql。

所以你的脚本可以重写为:

if db_id('Destination')is null
begin
    Create database Destination    
    exec ('select * into Destination.dbo.TabDestination from [Source].[dbo].[TabSource]')
end 
else
begin

    if exists (select name from Destination.sys.objects where name = 'TabDestination' and type = 'u')
    insert into Destination.dbo.TabDestination select * from [Source].[dbo].[TabSource]

end

答案 2 :(得分:1)

@Jon Egerton答案的变体,但有一个案例你忽略了:数据库存在,但表没有。

DECLARE @sql NVARCHAR(MAX) = N'SELECT * 
    INTO Destination.dbo.TabDestination 
    FROM Source.dbo.TabSource;';

IF DB_ID('Destination') IS NULL
BEGIN
    PRINT 'Creating database...';
    CREATE DATABASE Destination;
    PRINT 'Selecting into new table...';
    EXEC sp_executeSQL @sql;
END
ELSE
BEGIN
    IF EXISTS (SELECT 1 FROM Destination.sys.tables WHERE schema_id = 1 
        AND name = N'TabDestination')
    BEGIN
        PRINT 'Inserting into existing table...';
        INSERT Destination.dbo.TabDestination SELECT * FROM Source.dbo.TabSource;
    END
    ELSE
    BEGIN
        PRINT 'Selecting into new table...';
        EXEC sp_executeSQL @sql;
    END
END

修改

为调试目的添加了PRINT语句,正如我在@ Jon的回答中所建议的那样。

答案 3 :(得分:0)

你只需要摆脱GO命令,它是一个批处理分隔符,因此它会破坏你的开始/结束。哦,你不能像这样使用USE。