gpt4 book ai didi

sql-server - USE数据库切换后的GOTO标签

转载 作者:行者123 更新时间:2023-12-04 00:59:34 24 4
gpt4 key购买 nike

任何人都可以解释为什么这可行:

use MyDb1
if NOT EXISTS (select * from sys.objects where name = 'MyTable' and type = 'U' )
create table MyTable(MyColumn int not null)
use MyDb2
if NOT EXISTS (select * from sys.objects where name = 'MyTable' and type = 'U' )
create table MyTable(MyColumn int not null)


但这不是:

use MyDb1

mylabel:
if NOT EXISTS (select * from sys.objects where name = 'MyTable' and type = 'U' )
create table MyTable(MyColumn int not null)

if(DB_NAME()='MyDb1')
begin
use MyDb2
goto mylabel
end


流程是正确的,如果不存在,第二次检查是否有效,但是当尝试创建表时,出现以下错误


数据库中已经有一个名为“ MyTable”的对象。


这被大大简化了,但是使它起作用将为我节省两个几乎相同的数据库之间的大量重复表创建

最佳答案

非常奇怪的行为。如果我猜到了,我会说这是位​​于标签顶部的“使用数据库”的上下文。我永远不会在T-SQL中使用标签,而是您的要求。

该测试的输出显示它正在执行正确的运动,但无故失败。如果取消注释标记为<<<的行并对其上方的行进行注释,则它可以正常工作

set nocount on
use tempdb
create database db1
create database db2
GO

use db1

mylabel:
print 'in-' + db_name()
if NOT EXISTS (select * from sys.objects where name = 'MyTable' and type = 'U' )
begin
print 'create-' + db_name()
create table MyTable(MyColumn int not null)
-- exec ('create table MyTable(MyColumn int not null)') -- <<<
end

if(DB_NAME()='db1')
begin
print 'switch'
use db2
goto mylabel
end

GO
use tempdb
drop database db1
drop database db2


输出:

in-db1
create-db1
switch
in-db2
create-db2
Msg 2714, Level 16, State 6, Line 9
There is already an object named 'MyTable' in the database.

关于sql-server - USE数据库切换后的GOTO标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4754969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com