自动生成ID方法。
有数据库DB,字段ID
ID内容为7位数字。0000000-9999999,数据多了,比如已使用0000001,0000002..0000007,0000009,
这里面有0000003,0000004,0000005,0000006,0000008没有使用,怎么在使用的时候,增加一条数据自动从最小的计算出0000003,然后现增加的时候是0000004。
[解决办法]
解释一下,由于SQLServer没有那么大的参照表,所以要自己创建,你可以把#t定义为一个实体表,供以后使用。然后创建了这个参照表之后,下面表huang是测试的表,你改成你自己的表就可以了。下班了,有问题晚上再回复你[code=sql]IF OBJECT_ID('#t') IS NOT NULL[/code]
DROP TABLE #t
;WITH Digits AS (
SELECT 0 as Number
UNION SELECT 1
UNION SELECT 2
UNION SELECT 3
UNION SELECT 4
UNION SELECT 5
UNION SELECT 6
UNION SELECT 7
UNION SELECT 8
UNION SELECT 9
)
SELECT
(d5.Number * 100000)
+ (d4.Number * 10000)
+ (d3.Number * 1000)
+ (d2.Number * 100)
+ (d1.Number * 10)
+ d0.Number as Number INTO #t
FROM
Digits AS d0
, Digits AS d1
, Digits AS d2
, Digits AS d3
, Digits AS d4
, Digits AS d5
--SELECT * FROM #t ORDER BY Number
/*
IF OBJECT_ID('huang') IS NOT NULL
DROP TABLE huang
CREATE TABLE huang (id VARCHAR(7) )
INSERT INTO huang
SELECT '0000000'
UNION ALL SELECT '0000001'
UNION ALL SELECT '0000002'
UNION ALL SELECT '0000007'
UNION ALL SELECT '0000009'
*/
;WITH cte AS (
SELECT *
FROM huang a right JOIN #t b ON CAST(id AS int)=b.number
WHERE b.number<= (SELECT MAX(id) id FROM huang)
)
SELECT RIGHT('0000000'+CONVERT(VARCHAR(7),MIN(number)),7)
FROM cte
WHERE id IS NULL