Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Increment a Counter in a SELECT
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Posting Yak Master

105 Posts

Posted - 12/04/2012 :  14:32:35  Show Profile  Reply with Quote
I need to create a value in a column that increments.

A simple example would be:


SomeColumn as "Some Column",
'N2-L2' AS "Plan vs Instance"

FROM SomeTable

The key is, the number "2" (in 'N2-L2') needs to increment.

So, the value in the first selected row would be:


The value in the second selected row would be:


... and so on.

What is the best way to accomplish this?

Flowing Fount of Yak Knowledge

7174 Posts

Posted - 12/04/2012 :  14:41:28  Show Profile  Reply with Quote
How about you do with computed column.
Go to Top of Page

Flowing Fount of Yak Knowledge

5155 Posts

Posted - 12/04/2012 :  14:42:39  Show Profile  Reply with Quote
There is a discussion in this article:

One approach would be to create a computed column as in the example below:
	someCol VARCHAR(32), 
	id INT IDENTITY (1,1), 
	PlanVInstance AS 'N'+CAST(id AS VARCHAR(32))+'-L'+CAST(id AS VARCHAR(32))

INSERT INTO #tmp (someCol) VALUES ('abcd');
INSERT INTO #tmp (someCol) VALUES ('efgh');

SELECT somecol , PlanVInstance FROM #tmp;

Go to Top of Page

Flowing Fount of Yak Knowledge

7174 Posts

Posted - 12/04/2012 :  15:05:28  Show Profile  Reply with Quote
If you are trying to update or not use computed column

Update T
Set PlanVInstance = 'N' + cast(seq as Varchar(10))+ '-L' + cast(seq as Varchar(10))
from Table T
inner join
Select Id,ROW_NUMBER() OVER(ORDER by ID) as seq
from Table
)P on P.Id = T.Id

Edited by - sodeep on 12/04/2012 15:08:14
Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.04 seconds. Powered By: Snitz Forums 2000