我希望这是关于如何使用SQL语句检查SQL Server 2000/2005中是否存在表的最终讨论。

这里有两种可能的方法。哪一种是做这件事的标准/最佳方式?

第一个方法:

IF EXISTS (SELECT 1 
           FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_TYPE='BASE TABLE' 
           AND TABLE_NAME='mytablename') 
   SELECT 1 AS res ELSE SELECT 0 AS res;

第二种方式:

IF OBJECT_ID (N'mytablename', N'U') IS NOT NULL 
   SELECT 1 AS res ELSE SELECT 0 AS res;

MySQL提供简单的

SHOW TABLES LIKE '%tablename%'; 

声明。我在找类似的东西。


当前回答

我以创建一个视图为例。

因为ALTER/CREATE命令不能在BEGIN/END块中。在创建之前,您需要测试是否存在并删除它

IF Object_ID('TestView') IS NOT NULL
DROP VIEW TestView

GO

CREATE VIEW TestView
   as
   . . .

GO

如果您担心权限丢失,您也可以编写GRANT语句,并在最后重新运行它们。

你可以把create/alter包装成一个字符串,然后执行EXEC——对于大的视图来说,这可能会很难看

DECLARE @SQL as varchar(4000)

-- set to body of view
SET @SQL = 'SELECT X, Y, Z FROM TABLE' 

IF Object_ID('TestView') IS NULL
    SET @SQL = 'CREATE VIEW TestView AS ' + @SQL
ELSE    
    SET @SQL = 'ALTER VIEW TestView AS ' + @SQL

其他回答

IF EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE 
TABLE_CATALOG = 'Database Name' and
TABLE_NAME = 'Table Name' and 
TABLE_SCHEMA = 'Schema Name') -- Database and Schema name in where statement can be deleted

BEGIN
--TABLE EXISTS
END

ELSE BEGIN
--TABLE DOES NOT EXISTS
END

在SQL Server 2000中,您可以尝试:

IF EXISTS(SELECT 1 FROM sysobjects WHERE type = 'U' and name = 'MYTABLENAME')
BEGIN
   SELECT 1 AS 'res' 
END

在我的记忆中,我们总是使用OBJECT_ID样式

IF OBJECT_ID('*objectName*', 'U') IS NOT NULL 
select name from SysObjects where xType='U' and name like '%xxx%' order by name
IF OBJECT_ID('mytablename') IS NOT NULL