Please start any new threads on our new site at http://forums.sqlteam.com. 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
 
Register Now and get your question answered!
Username:
Password:
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  

planetoneautomation
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:

SELECT

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:

'N2-L2'

The value in the second selected row would be:

'N3-L3'

... and so on.

What is the best way to accomplish this?

sodeep
Flowing Fount of Yak Knowledge

USA
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

sunitabeck
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: http://www.sqlteam.com/article/custom-auto-generated-sequences-with-sql-server

One approach would be to create a computed column as in the example below:
CREATE TABLE #tmp 
(
	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;

DROP TABLE #tmp;
Go to Top of Page

sodeep
Flowing Fount of Yak Knowledge

USA
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.02 seconds. Powered By: Snitz Forums 2000