在下面的代码中,我可以使用表名和表架构指定要查询的表名称和架构。如何指定要查询的数据库名称和服务器名称?
我已经尝试过DATABASE_NAME,DB_NAME和SERVER_NAME。他们都不起作用。
SELECT COUNT(1) AS TABLECOUNT FROM INFORMATION_SCHEMA.TABLES WHERE
TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'CALCULATION_SCHEDULE'
答案 0 :(得分:3)
在这里,您可以选择数据库,表和服务器名称:
SELECT COUNT(1) AS TABLECOUNT, @@SERVERNAME as 'serverName' FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'CALCULATION_SCHEDULE'
and @@SERVERNAME ='xx' and TABLE_CATALOG ='database name'
单击here以了解有关serverName的更多信息
答案 1 :(得分:2)
您需要使用TABLE_CATALOG
来传递数据库名称。在SQL Server中,此列包含包含该表的数据库名称,如下所示。
SELECT COUNT(1) AS TABLECOUNT FROM INFORMATION_SCHEMA.TABLES WHERE
TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'CALCULATION_SCHEDULE'
AND TABLE_CATALOG = '<Your Database Name>'
您还可以直接传递服务器名称和数据库名称,如下所示。
SELECT * FROM [ServerName].[DatabaseName].INFORMATION_SCHEMA.TABLES where ---.
答案 2 :(得分:2)
没有表或视图枚举所有数据库的所有表,您必须明确指定数据库:
直接在查询中
SELECT COUNT(1) AS TABLECOUNT
FROM [dbname].INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'CALCULATION_SCHEDULE' ;
通过“ USE”
USE [dbname]
SELECT COUNT(1) AS TABLECOUNT
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'CALCULATION_SCHEDULE' ;
在您的连接字符串中
关于服务器名称,只能通过@@ SERVERNAME或SERVERPROPERTY('ServerName')之类的系统变量来实现:
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'CALCULATION_SCHEDULE'
AND SERVERPROPERTY('ServerName') = 'YourServer' ;