SqlServer数据库的语句及一些操作整理
临近年终,在工作之余对工作和学习中遇到的问题以及常用的一些知识点做了些整理,以备后用。本文涉及的内容为数据库,算是对开发总结(1)---数据库一文的补充。
1 对于主键设置了Identity的表,在删除表中数据后再往表中插入数据,Identity列不是从1起始了,如果想删除数据后Indentity列仍从1起始,可以用下面代码来删除数据。
truncate table tablename
DBCC CHECKIDENT(tablename,RESEED,1)
2 判断指定表在数据库中是否存在
if exists(select name from sysobjects where name='tablename' and type='u')
3 判断指定列在指定表中是否存在
if exists(select * from sys.columns,sys.tables
where sys.columns.object_id = sys.tables.object_id
and sys.tables.name='tablename' and sys.columns.[name]='columnname')
4 在编写代码生成器之类的程序的时候,通常需要取出数据库中所有的表名以及表中字段的一些基本信息,如字段长度、字段类型、描述等。实现上面要求的sql语句如下:
--取数据库中表的集合
select * from sysobjects where xtype='u' order by name
--取表中字段的一些基本信息
select
sys.columns.name, --字段名
sys.types.name as typename, --字段类型
sys.columns.max_length, --字段长度
sys.columns.is_nullable, --是否可空
(select
count(*)
from
sys.identity_columns
where
sys.identity_columns.object_id = sys.columns.object_id
and
sys.columns.column_id = sys.identity_columns.column_id
) as is_identity ,--是否自增
(select
value
from
sys.extended_properties
where
sys.extended_properties.major_id = sys.columns.object_id
and
sys.extended_properties.minor_id = sys.columns.column_id
) as description --注释
from
sys.columns, sys.tables, sys.types
where
sys.columns.object_id = sys.tables.object_id
and
sys.columns.system_type_id=sys.types.system_type_id
and
sys.tables.name='tablename'
order by sys.columns.column_id
5 在存储过程中使用事务
create procedure procname
as
begin tran
--执行sql语句
if @@ERROR!=0
begin
相关文档:
sqlserver2005有关键字ntile(x)和over(partition by.. order by..)子句配合.
比如获取每个表的前10%个字段。
select id , name , colid , rn from (
select * , rn = ntile (10 )
over (partition by id order by colorder )
from syscolumns )t where rn = 1 ......
SQLServer 中含自增主键的表,通常不能直接指定ID值插入,可以采用以下方法插入。
1. SQLServer 自增主键创建语法:
identity(seed, increment)
其中
seed 起始值
increment 增量
示例:
create table student(
id int identity(1,1),
name varcha ......
原文转自:http://dev.csdn.net/develop/article/71/71778.shtm
大多数SQL Server表需要索引来提高数据的访问速度,如果没有索引,SQL Server要进行表格扫描读取表中的每一个记录才能找到索要的数据。索引可以分为簇索引和非簇索引,簇索引通过重排表中的数据来提高数据的访问速度,而非簇索引则通过维护表中的数 ......
在用Asp.net对备份的数据库文件进行还原的时候,有时候会出现下面的错误异常:
[因为数据库正在使用,所以未能获得对数据库的排它访问权。 RESTORE DATABASE 操作异常终止。已将数据库上下文改为 'master'。]
这个时候,自由等待其他进程释放对应权限后,才可还原成功!有没有解决办法呢?我参照【Java】对这个问题的解决 ......