点击一个按钮,先检测数据库里有没有tableC(语句一)。
假如没有tableC,那么就新增tableC(语句二)
其中tableC
Id(Int) TypeName(varchar 100)
请问这两个语句应该如何写?
------解决方案--------------------
if object_id('tablec') IS NULL
create TABLE tablec
(
id int,
TypeName varchar (100)
)
go
SELECT * FROM dbo.tablec这样写多次运行不会报错。
------解决方案--------------------
如楼上所示,在程序中可以先用SQL语句判断:
select count(*) from sys.databases where name='tablec'
如果等于0的话,表示表不存在则创建表,否则表已经存在.
------解决方案--------------------
这样吗:
if not exists(select 1 from sys.tables where name='tablec')
create TABLE tablec(id int identity(1,1),TypeName varchar(100))
else
insert into tablec(TypeName)
values('7')
go
select *
from tablec
/*
id TypeName
1 7
*/
------解决方案--------------------
if not exists(select 1 from sys.tables where name='tableC') -- 语句一
begin
create table tableC -- 语句二
(Id int identity(1,1),
TypeName varchar(100))
end
else
begin
set identity_insert tableC on -- 语句三
insert into tableC(Id,TypeName) select 7,7
set identity_insert tableC off
end
------解决方案--------------------
if not exists(select 1 from sys.tables where name='tablec' and type = 'U')
begin
create table tablec(id int identity(1,1),TypeName varchar(100))
insert into tablec(TypeName) values('7')
end
else
insert into tablec(TypeName) values('7')