我想编写代码来检查 SQL Server 2008 中是否存在表,如果不存在则创建它,然后将记录插入其中。请告诉我该怎么做?是否有必要为其创建存储过程?
问问题
6191 次
3 回答
5
IF NOT EXISTS ( SELECT 1 FROM INFORMATION_SCHEMA.TABLES T
WHERE T.TABLE_SCHEMA = 'dbo'
AND T.TABLE_NAME = 'YOURTABLENAME' )
BEGIN
CREATE TABLE dbo.YOURTABLENAME
(
ColumnDefinitionsHere
)
END
GO
于 2013-08-23T09:54:00.760 回答
0
(SELECT count(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'TheSchema'
AND TABLE_NAME = 'TheTable')
如果 count 返回 0,则表示该表未退出
于 2013-08-23T09:55:55.373 回答
0
您需要查看系统视图来执行此操作:
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SomeTable]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[SomeTable](
[SomeId] [int] NOT NULL
)
END ELSE PRINT 'SomeTable already exists.';
于 2013-08-23T10:01:42.020 回答