检查表是否存在sql server

时间:2012-07-03 11:07:03

标签: java sql-server

  

可能重复:
  SQL Server: Check if table exists

我正在使用Java和MS SQL Server 2008,我想在检查数据库中是否存在表之后才创建表。

 public void addTestTable(){
  jdbcTemplate.execute(
            "create table [mydatabase].[dbo].[test] (ID integer not null identity, CREATEDBY varchar(50), CREATEDAT datetime, TITLE varchar(50), NRQUEST int, FORGROUP int, primary key(id))"

            );

}

这是我的createTable函数,我需要另一个布尔函数来检查表是否已经存在,但我不知道如何为它编写sql语句。有人可以帮帮我吗?

3 个答案:

答案 0 :(得分:1)

IF OBJECT_ID('tablename','U') is not null
-- table exists 

SELECT *
   FROM sys.tables
   WHERE name = 'mytable'
   AND schema_id = SCHEMA_ID('myschema')

答案 1 :(得分:0)

IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'testSchema' 
                 AND  TABLE_NAME = 'testTable')
BEGIN
    --create table
END

答案 2 :(得分:0)


if not exists(select 1 from sys.tables where name ='test' and schema_id = SCHEMA_ID('dbo'))
begin
  create table [dbo].[test] (ID integer not null identity, CREATEDBY varchar(50), 
  CREATEDAT datetime, TITLE varchar(50), NRQUEST int, FORGROUP int, primary key(id)) 
  print 'table created'
end
go