是否可以在该实例中的所有数据库都可以访问它的位置添加一个表?
由于
答案 0 :(得分:2)
您可以创建“主”数据库,并使用来自该SQL Server实例中任何其他数据库的SQL查询来访问它。这只是用户权限的问题。 table_or_view_name
的完整语法为database.schema.object_name
。
SELECT * FROM mytable AS t
INNER JOIN Main.dbo.SharedTable AS s ON t.Id=s.Id
....
Chack文档也是 - FROM (Transact-SQL)
答案 1 :(得分:0)
编辑:我添加了第二个解决方案。
第一个解决方案您可以尝试使用未经过补充的系统过程sp_msforeachdb:
EXEC sp_msforeachdb @command1=N'
USE ?;
IF ''?'' NOT IN (''master'',''model'',''tempdb'',''msdb'',''ReportServer'',''ReportServerTempDB'')
BEGIN
CREATE TABLE CocoJamboTable (
ID INT IDENTITY PRIMARY KEY,
FirstName NVARCHAR(50) NOT NULL,
LastName NVARCHAR(50) NOT NULL
);
END
';
EXEC sp_msforeachdb @command1=N'
USE ?;
IF ''?'' NOT IN (''master'',''model'',''tempdb'',''msdb'',''ReportServer'',''ReportServerTempDB'')
BEGIN
SELECT DB_NAME() AS DbName, name AS TableName, object_id FROM ?.sys.tables
WHERE name=''CocoJamboTable''
END
';
第二个解决方案您可以使用所有T-SQL
语句生成CREATE TABLE
脚本:
SET NOCOUNT ON;
PRINT 'BEGIN TRAN;'
/*
SELECT
'USE '
+ QUOTENAME(db.name)
+ ';'
+ '
CREATE TABLE CocoJamboTable (
ID INT IDENTITY PRIMARY KEY,
FirstName NVARCHAR(50) NOT NULL,
LastName NVARCHAR(50) NOT NULL
);'
+ CHAR(13)
*/
SELECT
CASE
WHEN db.name IN ('master','model','tempdb','msdb','ReportServer','ReportServerTempDB','ASPNETDB')
THEN '-- Explicit skipping: ' + QUOTENAME(db.name)
WHEN db.state <> 0
THEN '-- Implicit skipping (not online): ' + QUOTENAME(db.name)
WHEN db.is_read_only=1
THEN '-- Implicit skipping (read only): ' + QUOTENAME(db.name)
--WHEN other filter
-- THEN '-- Implicit skipping (my filter): ' + QUOTENAME(db.name)
ELSE
'CREATE TABLE ' + QUOTENAME(db.name) + '.dbo.CocoJamboTable (
ID INT IDENTITY PRIMARY KEY,
FirstName NVARCHAR(50) NOT NULL,
LastName NVARCHAR(50) NOT NULL
);'
END
+ CHAR(13)
FROM sys.databases db
ORDER BY db.name;
PRINT 'ROLLBACK;'
PRINT '-- COMMIT;'
然后,按Ctrl + T(文本结果),F5(执行),F6(跳转到文本结果面板),按Ctrl + A(全选),Ctrl + C(复制),Ctrl + N(新窗口) ,Ctrl + V(粘贴 - 粘贴上一步生成的脚本),F5(执行)。
示例T-SQL
脚本:
BEGIN TRAN;
CREATE TABLE [Comisioane].dbo.CocoJamboTable (
ID INT IDENTITY PRIMARY KEY,
FirstName NVARCHAR(50) NOT NULL,
LastName NVARCHAR(50) NOT NULL
);
-- Implicit skipping (read only): [Credite]
-- Explicit skipping: [master]
-- Explicit skipping: [model]
-- Explicit skipping: [msdb]
-- Explicit skipping: [ReportServer]
-- Explicit skipping: [ReportServerTempDB]
CREATE TABLE [SIMUR4].dbo.CocoJamboTable (
ID INT IDENTITY PRIMARY KEY,
FirstName NVARCHAR(50) NOT NULL,
LastName NVARCHAR(50) NOT NULL
);
ROLLBACK;
-- COMMIT;