查询更新行,然后创建表(如果不存在)

时间:2011-09-29 14:41:41

标签: sql sql-server-2008

我有两个不同的事情一次发生..,基本上我需要在表中插入两个新记录,如果它们还没有...并且肯定他们将始终具有相同的ID和名称(我做了这个)但之后我需要检查一个表是否存在,如果它没有创建它...(但如果确实存在,我不想放弃它只是不管它。)

请参阅下面的代码..您可以帮我检查现有的表格吗?如果你看到一个改进的房间,请做..

谢谢

--ADD LOCKS
BEGIN TRAN
IF EXISTS (SELECT myID, myName 
           FROM myTable
           WHERE myID = 7 AND myName = 'Pedro') 
               SELECT 1 
ELSE
      INSERT INTO myTable (myID , myName) values ( 7, 'Pedro')    

IF EXISTS (SELECT myID, myName 
           FROM myTable
           WHERE myID = 8 AND myName = 'Joseph') 
               SELECT 1 
ELSE
      INSERT INTO myTable (myID , myName) values ( 8, 'Joseph')    
COMMIT

--NOW BELOW I WANT TO DO THE CREATION OF A TABLE IF IT DOES NOT EXIST

不确定如何检查它......但是知道如何创建它

--IF TABLE DOES NOT EXIST DO THE FOLLOWING
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[myTable](
    [myID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar(MAX)] NOT NULL
 CONSTRAINT [PK_myTable] PRIMARY KEY CLUSTERED 
(
    [myID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

--ELSE DONT DO NOTHING

2 个答案:

答案 0 :(得分:1)

据我所知,您先检查表是否存在,然后在插入之前创建表(如果该表不存在)。希望以下查询对您有用。

     IF NOT EXISTS (SELECT * FROM SYSOBJECTS WHERE ID = OBJECT_ID(N'[dbo].[myTable]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
     BEGIN
CREATE TABLE [dbo].[myTable]
(     
    [myID] [int] IDENTITY(1,1) NOT NULL,     
    [Name] [varchar(MAX)] NOT NULL  
    CONSTRAINT [PK_myTable] PRIMARY KEY CLUSTERED  
    (     [myID] ASC 
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON
) ON [PRIMARY] ) ON [PRIMARY] 
    END

    IF NOT EXISTS (SELECT myID, myName  FROM myTable WHERE myID = 7 AND myName = 'Pedro')  
    BEGIN  
           INSERT INTO myTable (myID , myName) values ( 7, 'Pedro')    
   END  

   IF NOT EXISTS (SELECT myID, myName  FROM myTable WHERE myID = 8 AND myName = 'Joseph')  
    BEGIN  
        INSERT INTO myTable (myID , myName) values ( 8, 'Joseph')    
    END 

编辑:还应注意,如果不打开IDENTITY_INSERT,这将无效。由于myID列是标识字段,因此尝试插入的值将失败。

答案 1 :(得分:0)

为了插入记录,清洁脚本将是:

IF NOT EXISTS (SELECT 1 FROM myTable WHERE ...)
BEGIN
    -- Insert record
END

并检查表是否存在: Check if table exists in SQL Server

IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TheSchema' AND  TABLE_NAME = 'TheTable'))
BEGIN
    -- Insert table
END

您可能希望切换这些语句的顺序,以便不查询可能不存在的表。