如何向SQL Server 2008添加新架构?


68

如何将新架构添加到数据库?我正在创建一个新表,并想从属性列表中选择自己的模式,但是我不知道如何创建它。我正在使用SQL Server Management 2008。

Answers:



50

这是一个技巧,可以轻松地检查模式是否已经存在,然后在其自己的批处理中创建它,以避免在不是批处理中唯一的命令时尝试创建模式的错误消息。

IF NOT EXISTS (SELECT schema_name 
    FROM information_schema.schemata 
    WHERE schema_name = 'newSchemaName' )
BEGIN
    EXEC sp_executesql N'CREATE SCHEMA NewSchemaName;';
END

11

我用这样的东西:

if schema_id('newSchema') is null
    exec('create schema newSchema');

这样做的好处是,如果您在较长的sql脚本中包含此代码,则始终可以与其他代码及其简短代码一起执行。


8

将模式添加到现有表的最佳方法:右键单击特定表->设计->在Management Studio下,右键单击Properties窗口并选择模式,然后单击它,然后查看下拉列表并选择模式。更改后,请保存架构。然后将看到它将改变您的架构。


7

您可以尝试以下方法:

use database
go

declare @temp as int
select @temp = count(1) from sys.schemas where name = 'newSchema'

if @temp = 0 
begin
    exec ('create SCHEMA temporal')
    print 'The schema newSchema was created in database'
end 
else 
print 'The schema newSchema already exists in database'
go

1
我学会的一种快速方法是这样的:如果存在(从sys.schemas中选择名称,其中name ='newschema')
— 标记

好的,没关系,您可以自己运行此检查,但是只有在其自己的批处理中时,创建架构才有效。
— 2014年

1

在SQL Server 2016 SSMS中,展开'DATABASNAME'>展开'SECURITY'>展开'SCHEMA'; 右键单击弹出窗口中的“ SCHEMAS”,然后单击“ NEW SCHEMAS ...”,在打开的窗口中添加名称并添加所有者,即dbo单击“确定”按钮


这也适用于Microsoft SQL Server Management Studio(SSMS)2012版本。
— 亚瑟·曾尼格
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.