您的位置:首页 > 数据库

判断SQL数据库是否存在表,是否存在记录

2014-04-04 15:39 239 查看
SQL数据库,当判断一条记录存在时,则更新更记录,当记录不存在时,则添加该记录

使用SQL语句在C#中实现,sql语句

if exists

(select * from 表 where 条件)

begin

Update 表 Set 字段=字段值 where 条件

end

else

begin

Insert into dbo.表名(字段) values

(字段值)

end

比如:

if exists

(select * from CollectRain_201404 where StationId='D6021' and CollectTime='20140406232000')

begin

Update CollectRain_201404 Set CollectRainFall='22222',IsValue='false' where StationId='D6021' and CollectTime='20140406232000'

end

else

begin

Insert into dbo.CollectRain_201404 (StationId,CollectTime,CollectRainFall,IsValue) values

('D6021','20140406232000','11111','true')

end

当判断一个表是否存在数据库时,当数据库不存在该表时,则需要新建该表

使用SQL在C# NET中实现方法

if exists

(select * from sysobjects where id = object_id(N'[表名]')

and OBJECTPROPERTY(id, N'IsUserTable') = 1)

print 'f'

else

begin

CREATE TABLE 表名

(

建表

)

end

比如

if exists

(select * from sysobjects where id = object_id(N'[Test]')

and OBJECTPROPERTY(id, N'IsUserTable') = 1)

print 'f'

else

begin

CREATE TABLE Test

(

Id int IDENTITY(1,1) PRIMARY KEY,

StationId nvarchar(MAX) NOT NULL,

CollectTime nvarchar(MAX) not null,

CollectRainFall float not null,

IsValue bit not null

)

end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: