Riaan Lehmkuhl's Blog

Subversion, Progamming, Tips & Tricks and whatever else springs to mind.
19Jun

Adding an Ordinal column using a sub query

19 June 2008 23:10 by Riaan Lehmkuhl
This is just a simple way of adding an ordinal column to a SQL result using a sub query. This method depends on the Primary Key field of the table. I used the Northwind database for this example.
The idea is to select the Products with an ordinal numbered column...
Ordinal ProductID ProductName CategoryID
1 11 Queso Cabrales 4
2 12 Queso Manchego La Pastora 4
3 31 Gorgonzola Telino 4
4 32 Mascarpone Fabioli 4
5 33 Geitost 4

To do this I've created the following stored procedure with the CategoryID is an optional parameter:
CREATE PROCEDURE [dbo].[sp_SelectProducts]
(
@CategoryID INT = NULL
)
AS
DECLARE @sql NVARCHAR(4000)
SET @sql = N'
SELECT top 5 (SELECT COUNT(*) 
FROM Products p 
WHERE p.ProductID <= Products.ProductID '
IF (@CategoryID IS NOT NULL) BEGIN
SET @sql = @sql + N' AND p.CategoryID = Products.CategoryID '
END
SET @sql = @sql + N') AS Ordinal,
ProductID,
ProductName,
CategoryID,
QuantityPerUnit,
UnitPrice,
UnitsInStock,
UnitsOnOrder,
ReorderLevel
FROM Products
WHERE Discontinued != 1'
IF (@CategoryID IS NOT NULL) BEGIN
SET @sql = @sql + N' AND CategoryID = ' + CAST(@CategoryID AS NVARCHAR)
END
EXEC sp_executesql @sql;
For each product that is returned we get it's ordinal position by counting the ProductIDs already returned and it self.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Comments are closed

Riaan Lehmkuhl


Me, a disorder of the brain that results in a disruption in a person's thinking, mood, and ability to relate to others.

Recent comments

Comment RSS

Thingies

Calendar And Month List

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

Disclaimer & Privacy

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008

Privacy:
We use third-party advertising companies to serve ads when you visit our website. These companies may use information (not including your name, address, email address, or telephone number) about your visits to this and other websites in order to provide advertisements about goods and services of interest to you. If you would like more information about this practice and to know your choices about not having this information used by these companies, click here.

Most comments

Cool Quote

I know that you believe that you understood what you think I said, but I am not sure you realize that what you heard is not what I meant. - Robert McCloskey