Tables created by default in user schema

本小妞迷上赌 提交于 2019-12-22 11:35:23

问题


In Sql Server 2008, when I create a table without schema prefix:

create table mytable ( id int identify )

it usually ends up in the schema dbo, with name dbo.mytable.

However, on one of our servers, the tabel ends up belonging to me:

andomar.mytable

Which configuration difference could explain this?


回答1:


It depends what your default schema is within that database. Even in SQL Server 2005, if your default schema in that one database is andomar, then any tables created without an explicit schema will end up there.

Check the user properties in that database (not the login properties) and see what the default schema is.




回答2:


If you don't define schema in which you create table it will always use default one. you can create it like this:

USE DataBaseName -- define database to use
GO
BEGIN TRAN - if you will have any error everything will roll back
CREATE TABLE testovi.razine - schema name is "testovi" and tablename is "razine"
(
id INT NOT NULL IDENTITY(1,1),
razina NVARCHAR(50) NULL,
razinaENG NVARCHAR(50) NULL,
kreirao UNIQUEIDENTIFIER NULL,
VrijemeKreiranja DATETIME NULL
)
ON [PRIMARY]
GO

When you create table always set constraint and index on column most used for transaction

ALTER TABLE testovi.razine ADD CONSTRAINT
PK_mat_razine PRIMARY KEY CLUSTERED
(id) WITH(IGNORE_DUP_KEY=OFF,  --check duplicate and don't ignore if try to insert one
STATISTICS_NORECOMPUTE=OFF,  -- important for statistic update and query optimization
ALLOW_PAGE_LOCKS=ON) -* I believe that this is default, but always put it to on if not
ON [PRIMARY]
GO
if @@error<>0
BEGIN
ROLBACK TRAN
END
ELSE
BEGIN 
COMMIT TRAN --if everything passed o.k. table will be created
END

If you want to set default schema you have to know that it is user based default so you can set it with code:

USE espabiz -- database;
ALTER USER YourUserName WITH DERAULT_SCHEMA = SchemaName; -- SchemaName is default schema for defined user

Ping if you need additional help or mark answer it you find it usable :)



来源:https://stackoverflow.com/questions/863028/tables-created-by-default-in-user-schema

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!