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

Problem Solving: Create Scalar-valued Function

$
0
0

Environment: SQL server 2005 and Win7
Tools: MS SQL Management studio 2008 R2
Problem: How to create scalar-valued function, which generates randomly ID Numbers. Those Id number must be 9 char in length and don't exist in the dbo.Table_people nor dbo.Table_ssn
Code:

Create Function keygen_pn_id (@get Char(1))

Returns char(9) AS Begin IF (@get=0) DECLARE @new_nbr CHAR(9), @len INT

SELECT @new_nbr = ltrim(rtrim(convert(CHAR(9),convert(int,(RAND()*1000000000))))) -- check if the generated ID number whether exists on both tables. If does not exist then assign new_nbr to pn_id otherwise skip and generate a new number. If not exists (Select pn_id from dbo.Table_people where pn_id=@new_nbr) and (select pn_id from Table_ssn where pn_id=@newnbr) Return @new_nbr END


Viewing all articles
Browse latest Browse all 23857

Trending Articles



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