日期:2014-05-16  浏览次数:20690 次

这两个语句应该怎么写?
点击一个按钮,先检测数据库里有没有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的话,表示表不存在则创建表,否则表已经存在.

------解决方案--------------------
引用:
Quote: 引用:

sql server 2000的:
if not exists(select 1 from sysobjects where name='tablec' and type = 'U')
  create TABLE tablec(id int,TypeName varchar(100))
go


sql server 2005及以上的版本:


if not exists(select 1 from sys.tables where name='tablec')
  create TABLE tablec(id int,TypeName varchar(100))
go




不好意思,一开始的需求我没写全,
完整的需求是这样的:

点击一个按钮,先检测数据库里有没有tableC(语句一)。
假如没有tableC,那么就新增tableC(语句二)

其中tableC
Id(Int) (并且Id设置为自增长Id))        TypeName(varchar  100)


假如有tableC,那么就往tableC里插入一个数据(7)(7只是一个例子,具体的数据是动态的)(语句三)



这样吗:
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 ta