Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Get Sequence Number from Scalar Function

$
0
0

I have a scalar function that I would like y'all to critique.  Below is some code to create a test table, insert some data, create the scalar function I use to get the QuoteNumber, select the data using the function, and dropping the table and function.

I currently use an embedded query in the function and I was wondering if there is a more efficient way of doing it?

-- create a test table
CREATE TABLE [dbo].[test](
	[QuoteID] [int] NOT NULL,
	[QuoteCreateDate] [datetime] NOT NULL
CONSTRAINT [PK_test] PRIMARY KEY CLUSTERED ([QuoteID] ASC, [QuoteCreateDate] ASC)
WITH (PAD_INDEX  = OFF, 
STATISTICS_NORECOMPUTE  = OFF, 
IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS  = ON, 
ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO


-- insert some test date
insert into test
values (1, '6-16-2014'),
		(1, '6-17-2014'),
		(2, '6-18-2014')
GO


-- create scalar function
CREATE FUNCTION [dbo].[fn_test]
(
	@QuoteID int,
	@QuoteCreateDate datetime
)
RETURNS varchar(14)
AS
BEGIN

	DECLARE @QuoteNumber varchar(14);
	
	with QuoteNumbers as
	(
	select QuoteID, QuoteCreateDate,
		cast(QuoteID as varchar(10)) + '-' + cast(ROW_NUMBER() OVER (PARTITION BY QuoteID ORDER BY QuoteCreateDate) as varchar(4)) as QuoteNumber
	from dbo.test
	where QuoteID = @QuoteID
	)
	select @QuoteNumber = QuoteNumber
	from QuoteNumbers
	where QuoteID = @QuoteID
		and QuoteCreateDate = @QuoteCreateDate

	return @QuoteNumber
END
GO

-- select the data to show the QuoteNumber format I'd like
select dbo.fn_test(QuoteID, QuoteCreateDate) as QuoteNumber, *
from dbo.test
GO

-- clean up
DROP TABLE dbo.test
DROP FUNCTION dbo.fn_test
GO


Ryan


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>