April 26, 2004 at 1:53 am
Can soemone show me how to do this in an UDF.
say i want to have a list of records such as these...
Cust No Tel No Seq No
100 1234 1
100 1235 2
200 3333 1
200 2233 2
200 2345 3
300 4444 1
The sequence will be for a group of same cust no but unique Tel No and will recycle back to 1 on the next group of cust no..
Pls help me!! Thanks
April 26, 2004 at 2:03 am
Quick and dirty, this should work
select Cust_No, Tel_No,
(SELECT COUNT(*)
FROM
WHERE Cust_No = s.Cust_No
AND Tel_No <= s.Tel_No) AS Seq_No
FROM s
This might also be interesting
--
Frank Kalis
Microsoft SQL Server MVP
Webmaster: http://www.insidesql.org/blogs
My blog: http://www.insidesql.org/blogs/frankkalis/[/url]
April 26, 2004 at 2:35 am
hey hey.. it works. Thanks man!!
April 26, 2004 at 2:35 am
I'd suggest modifying as follows :
select Cust_No, Tel_No,
(SELECT COUNT(*) + 1
FROM
WHERE Cust_No = s.Cust_No
AND Tel_No s.Tel_No) AS Seq_No
FROM s
This will give the next available sequence number, rather than the last used, and will allow for telephone numbers which are not always added in ascending order
April 27, 2004 at 9:10 pm
/* CODE BETTER, FUNCTION BETTER */
-- Your code should read like it runs
-- FIRST make sure you have an index like
CREATE INDEX <tablename>_001 ON <tablename> (Cus_No,Tel_No);
-- SECOND create UDF(from above examples SP's)
-- to use for calculating your Seq_No
-- for each new record as they are added
CREATE FUNCTION getSeq(@Cus_No integer, @Tel_No integer)
RETURNS integer
AS
BEGIN
DECLARE @Seq_No integer
SELECT @Seq_No = count(*)
FROM <tablename> (NOLOCK INDEX=<tablename>_001)
WHERE Cus_No = @Cus_No
AND Tel_No <= @Tel_No
RETURN @Seq_No
END
-- Ha, now you can use it in your query:
SELECT *, getSeq(Cus_No,Tel_No) FROM <tablename>
-- or use this function as a
-- YES! a computed column to your <tablename>
-- Alter table with a calculated column
ALTER TABLE <tablename>
ADD Seq_No AS getSeq (Cus_No,Tel_No)
Coach James
April 28, 2004 at 12:56 am
Just out of curiosity, James.
Why a UDF?
--
Frank Kalis
Microsoft SQL Server MVP
Webmaster: http://www.insidesql.org/blogs
My blog: http://www.insidesql.org/blogs/frankkalis/[/url]
April 29, 2004 at 8:33 pm
I'm suggesting a UDF as CALCULATED COLUMN
--- see last line ---
Coach James
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply