Category Archives: SQL

Reset Identity Column Value in SQL Server (转)

If you are using an identity column on your SQL Server tables, you can set the next insert value to whatever value you want. An example is if you wanted to start numbering your ID column at 1000 instead of 1.

It would be wise to first check what the current identify value is. We can use this command to do so:

DBCC CHECKIDENT (’tablename’, NORESEED)

For instance, if I wanted to check the next ID value of my orders table, I could use this command:

DBCC CHECKIDENT (orders, NORESEED)

To set the value of the next ID to be 1000, I can use this command:

DBCC CHECKIDENT (orders, RESEED, 999)

Note that the next value will be whatever you reseed with + 1, so in this case I set it to 999 so that the next value will be 1000.

Another thing to note is that you may need to enclose the table name in single quotes or square brackets if you are referencing by a full path, or if your table name has spaces in it. (which it really shouldn’t)

DBCC CHECKIDENT ( ‘databasename.dbo.orders’,RESEED, 999)

如何选出所有子类

–测试数据
CREATE   TABLE   tb(ID   char(3),PID   char(3),Name   nvarchar(10))
INSERT   tb   SELECT   ‘001’,NULL   ,’山东省’
UNION   ALL   SELECT   ‘002’,’001′,’烟台市’
UNION   ALL   SELECT   ‘004’,’002′,’招远市’
UNION   ALL   SELECT   ‘003’,’001′,’青岛市’
UNION   ALL   SELECT   ‘005’,NULL   ,’四会市’
UNION   ALL   SELECT   ‘006’,’005′,’清远市’
UNION   ALL   SELECT   ‘007’,’006′,’小分市’
GO

–查询指定节点及其所有子节点的函数
CREATE   FUNCTION   f_Cid(@ID   char(3))
RETURNS   @t_Level   TABLE(ID   char(3),Level   int)
AS
BEGIN
DECLARE   @Level   int
SET   @Level=1
INSERT   @t_Level   SELECT   @ID,@Level
WHILE   @@ROWCOUNT>0
BEGIN
SET   @Level=@Level+1
INSERT   @t_Level   SELECT   a.ID,@Level
FROM   tb   a,@t_Level   b
WHERE   a.PID=b.ID
AND   b.Level=@Level-1
END
RETURN
END
GO

–调用函数查询002及其所有子节点
SELECT   a.*
FROM   tb   a,f_Cid(‘002’)   b
WHERE   a.ID=b.ID
/*–结果
ID       PID     Name
——   ——-   ———-
002     001     烟台市
004     002     招远市
–*/
原文:http://topic.csdn.net/t/20051031/13/4361341.html