我想在SQL Server 2008中编写代码以检查表是否已存在,如果不存在,则创建它然后将记录插入其中。 请告诉我怎么做? 是否有必要为它创建存储过程?
答案 0 :(得分:4)
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
答案 1 :(得分:0)
(SELECT count(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'TheSchema'
AND TABLE_NAME = 'TheTable')
如果count返回0表示该表未退出
答案 2 :(得分: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.';