我正在使用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语句。有人可以帮帮我吗?
答案 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