IDENTITY(标识)列,也有很多人称之为自增列,在sql server 2000中,标识列通过IDENTITY来定义,下面是与获取最后插入记录的标识值有关的函数的一个示例说明
SQL Server 中,可以使用 SCOPE_IDENTITY()、 @@IDENTITY 、 IDENT_CURRENT() 来取得最后插入记录的值值,它们的区别在于:
SCOPE_IDENTITY() 返回插入到同一作用域中的 IDENTITY 列内的最后一个 IDENTITY 值。一个作用域就是一个模块存储过程、触发器、函数或批处理。因此,如果两个语句处于同一个存储过程、函数或批处理中,则它们位于相同的作用域中。
@@IDENTITY 返回在当前会话的所有表中生成的最后一个标识值
IDENT_CURRENT() 返回为任何会话和任何作用域中的指定表最后生成的标识值
当一个表中的记录删除后如果再新加,SQL会在原来的 IDENTITY 基础上增加.我们可以用下面的命令来复位
DBCC CHECKIDENT(表名,RESEED,0)
下面是从一个朋友的Blog上传过来的.清空整个数据库的SQL语句
SET NoCount ON
DECLARE @tableName varchar(512)
Declare @SQL varchar(2048)
SET @tableName=''
WHILE EXISTS
(
--Find all child tables and those which have no relations
SELECT T.table_name FROM INFORMATION_SCHEMA.TABLES T
LEFT OUTER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC ON T.table_name = TC.table_name
WHERE ( TC.constraint_Type = 'Foreign Key' OR TC.constraint_Type IS NULL )
AND T.table_name NOT IN ( 'dtproperties', 'sysconstraints', 'syssegments' )
AND Table_type = 'BASE TABLE'
AND T.table_name > @TableName
)
Begin
SELECT @tableName = min(T.table_name) FROM INFORMATION_SCHEMA.TABLES T
LEFT OUTER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC ON T.table_name=TC.table_name
WHERE ( TC.constraint_Type = 'Foreign Key' OR TC.constraint_Type IS NULL )
AND T.table_name NOT IN ( 'dtproperties', 'sysconstraints', 'syssegments' )
AND Table_type = 'BASE TABLE'
AND T.table_name > @TableName
--Truncate the table
SET @SQL = 'Truncate table '+ @TableName
print (@SQL)
Exec(@SQL)
End
SET @TableName=''
WHILE EXISTS
(
--Find all Parent tables
SELECT T.table_name FROM INFORMATION_SCHEMA.TABLES T
LEFT OUTER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC ON T.table_name = TC.table_name
WHERE TC.constraint_Type = 'Primary Key'
AND T.table_name <> 'dtproperties'
AND Table_type='BASE TABLE'
AND T.table_name > @TableName
)
Begin
SELECT @tableName = min(T.table_name) FROM INFORMATION_SCHEMA.TABLES T
LEFT OUTER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC ON T.table_name=TC.table_name
WHERE TC.constraint_Type = 'Primary Key'
AND T.table_name <> 'dtproperties'
AND Table_type = 'BASE TABLE'
AND T.table_name > @TableName
--Delete the table
SET @SQL = ' delete from '+ @TableName
print (@SQL)
Exec(@SQL)
--Reset identity column
IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMNPROPERTY(
OBJECT_ID( QUOTENAME(table_schema)+ '.' + QUOTENAME(@tableName) ),
column_name,'IsIdentity'
) = 1
)
DBCC CHECKIDENT(@tableName,RESEED,0)
End
SET NoCount OFF1、先找出没有外键约束的表,truncate
2、有外键的表,先delete,再复位identity列
于是得出,
语句丁(注意没有使用游标)
原文地址:http://www.cnblogs.com/downmoon/archive/2009/09/11/1564391.html
请参见