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
相关文档:
SQL Server 2008 Administration Instant Reference
SQL Server 2005 数据库基础与应用技术
Microsoft SQLServer 2005 Integration Services Step by Step
SQLServer 2005 Bible
SQL Server 2005 数据库服务架构设 ......
Sqlserver得到汉字拼音首字母存储过程:
create function [dbo].[fun_getPY]
(
@str nvarchar(4000)
)
returns nvarchar(4000)
as
begin
declare @word nchar(1),@PY nvarchar(4000)
set @PY=''
while len(@str)>0
begin
set @word=left(@str,1)
--如果非汉字字符,返回原字符
& ......
最近整理出来的.如果不完全的话希望大家补充.
在access中,转换为大写的sql函数是ucase,在sqlserver中,转换为大写的函数是upper;在access中,转换为小写的函数是lcase,在sqlserver中,转换为小写的函数是lower;在access中,取当前时间的函数是now,另外还有一个取日期函数date,在sqlserver中,取当前的函数是getdate ......
在Google上使用“sql 分页”关键字进行搜索,几乎所有的答案都是那三条。其二效率最高,其三使用游标,效率最差。
下面是那三种方法 (插入代码没有sql选项)
方法1:
适用于 SQL Server 2000/2005
SELECT TOP 页大小 *
from table1
WHERE ......