Hi There,
I want to create a column that usto numbers upto a specified value, and the resets. I've tried using the identity column and then using DBCC CHECKIDENT, but this doesnt doesn't have the desired affect. Here's an example of what I'm after.
AutoRow
1
2
3
4 --- reset
1
2
3
4 ---reset
Any help would be great,
many thanks
Stuart
An indentity field is going to require unique values, so reseting it isnt going to work, your going to throw an SQL Exception.
Are you trying to accomplish this just on the SQL server, or can you do it as part of your application?
|||Unfortuanatley it needs to be done on the server|||Check this sample to see whether it helps:
DROP TABLE tbl_testIden
go
CREATE TABLE tbl_testIden (id int identity(1,1), name sysname)
GO
CREATE TRIGGER trg_tsetIden ON tbl_testIden FOR INSERT,UPDATE
AS
IF (IDENT_CURRENT('tbl_testIden')>=4)
DBCC CHECKIDENT('tbl_testIden',RESEED,0)
GO
DECLARE @.i INT
SET @.i=1
WHILE (@.i<100)
BEGIN
INSERT INTO tbl_testIden(name) SELECT 'Person#'+CONVERT(VARCHAR(8),@.i)
SET @.i=@.i+1
END
go
SELECT * FROM tbl_testIden
|||
Hi There,
I managed to get it working using the Row_Number function. It has some very useul derivetives also.
Row_Number simply creates and incremental list which is reset when thepartiation by value changes.
ROW_NUMBER()OVER(PARTITIONBY ReqPointIdORDERBY ReqPointIdDESC)AS RowGroup
I'll look at your approach as it alows me to specify and upper limit.
Many thanks for your time
Regards
Stuart
|||
You are looking for a combination of ROW_NUMBER and %, but without more of the query, I can't help you. Generically...
SELECT (RowGroup % 4)+1 As AutoGen, more columns here
FROM (
SELECT ROW_NUMBER() OVER (something) AS RowGroup, more columns here
) t1
You may even be able to combine the two, but I'm not familiar enough with ROW_NUMBER to say that would work, but if it does... Then...
SELECT (ROW_NUMBER() OVER (something) % 4)+1 AS RowGroup, more columns here
FROM somewhere
should work as well. I think most people (myself included) were confused because you said you wanted an autogenerated column. That tends to lead people to believe you are speaking of a table column, not a field in a resultset.
No comments:
Post a Comment