在检查表是否存在后,在SQL中为一个遗漏的表添加模式。

8 浏览
0 Comments

在检查表是否存在后,在SQL中为一个遗漏的表添加模式。

我正在尝试为遗漏的表'myTable'添加模式。我希望将该表放在'dbo.myTable'下方。

编辑

我无法添加代码,但是堆栈溢出不允许..我想要从sys.tables中检查是否存在,并执行alter schema转移。

0
0 Comments

问题的出现原因是在SQL中,一个表总是属于一个模式(schema),如果没有指定其他模式,它将属于默认的dbo模式。

To check if a table exists in SQL Server, you can use the "IF EXISTS" statement along with the "OBJECT_ID" function.

要检查一个表在SQL Server中是否存在,可以使用"IF EXISTS"语句和"OBJECT_ID"函数。

Here is an example of how to check if a table exists before adding a schema to it:

IF EXISTS (SELECT 1 FROM sys.tables WHERE name = 'YourTableName')
BEGIN
    ALTER SCHEMA YourSchemaName TRANSFER dbo.YourTableName;
END

In this example, it checks if a table with the name 'YourTableName' exists in the sys.tables system view. If it exists, the ALTER SCHEMA statement is executed to transfer the table to the specified schema (YourSchemaName).

如果存在,就执行ALTER SCHEMA语句将表转移到指定的模式(YourSchemaName)。

This approach ensures that the schema is added to the table only if the table exists, avoiding any errors that may occur if the table doesn't exist.

这种方法确保只有当表存在时才向表中添加模式,避免了表不存在时可能出现的错误。

It is important to note that the schema specified in the ALTER SCHEMA statement must already exist in the database. If the schema doesn't exist, you will need to create it before using the ALTER SCHEMA statement.

需要注意的是,ALTER SCHEMA语句中指定的模式必须已经存在于数据库中。如果模式不存在,需要在使用ALTER SCHEMA语句之前先创建它。

In conclusion, to add a schema to a missed table in SQL after checking if the table exists, you can use the "IF EXISTS" statement along with the "OBJECT_ID" function to check if the table exists. If it exists, you can use the ALTER SCHEMA statement to transfer the table to the specified schema. This approach ensures that the schema is added to the table only if it exists, avoiding any errors.

0
0 Comments

问题的出现原因是:当在SQL中添加schema到一个已经存在的表时,需要先检查该表是否存在,如果存在则执行alter schema命令进行添加。解决方法是使用sys.objects表来检查表是否存在,并根据检查结果执行alter schema命令。

以下是完整文章的内容:

默认的schema是dbo,但如果由于某种原因它在不同的schema中,你可以使用alter schema命令将表转移到指定的schema中。

为了在表存在的情况下转移schema,你可以使用以下代码:

if exists (select 1
           from sys.objects o
           where schema_name(o.schema_id)<>N'dbo'
             and o.name = 'mytable'
           )
alter schema dbo transfer test.mytable;

rextester演示:http://rextester.com/TEBRQL57704

是否有一种方法可以通过sys.tables来检查表是否存在,并执行alter schema命令?

是的,这是可能的。

0