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

How to update an ID using a stored procedure in table #2

$
0
0

Environment: Win7 and SQL server 2008 R@

Tools: SQL management tool 2008 R2

T-SQL code - works fine- :

CREATE TABLE employees
( 
  id char(9),
  employee_number int not null,
  employee_name varchar(50) not null,
  salary int,
  CONSTRAINT employees_pk PRIMARY KEY (employee_number)
);


INSERT INTO employees (employee_number, employee_name, salary) VALUES (1001, 'Sally Johnson', 32000); 
INSERT INTO employees (employee_number, employee_name, salary) VALUES (1002, 'Will Smith', 38000); 
INSERT INTO employees (employee_number, employee_name, salary) VALUES (1003, 'Jessica simpson', 32000); 
INSERT INTO employees (employee_number, employee_name, salary) VALUES (1004, 'Michael Lira', 65000); 


Select * From employees


GO

Create VIEW [dbo].[vwRand]
AS
	Select Right('000000000'+LTRIM(RTRIM(STR(RAND()*1000000000))),9) as Rand


GO


Create function dbo.[fn_gen_id]()
RETURNS int
 as
    begin
          DECLARE @Random varchar(9);

    SELECT @Random = Rand
    FROM vwRand return @Random end; GO update a Set Id= (Select [dbo].[fn_gen_id]()) From employees a Select * From employees

Problem: There is a table called "people" which consist of SSN, ID, and employee_number. The ID is already stored in the table. The problem is that function could generate duplicate ID numbers and may have already ID numbers exist in the people table. How I would generate unique ID numbers in the above function of which don't exist in the people table and they are all unique. I tried a couple ways and my all attempts have failed.

Example to illustrate:

Employee table (ID, employee_number, name, salary)
(288258466, 1001, Sally Johnson, 32000)
(176268917, 1002, Will Smith, 38000)
(900303787, 1003, Jessica simpson, 32000)
(704099635, 1004, Michael Lira, 65000)
(704099640, 1005, Douglas Mike, 24000 )
(288258450, 1006, Susan jesson, 32000)
(176268960, 1007, Veronica floris, 100000)
(900303770, 1008, Miami chab, 250000)

People table: (SSN.ID,employee_number)

(219223434,288258466, 1001)
(012346787,176268917, 1002)
(123456789,900303787, 1003 )
(987654321,704099640, 1005 )
(212345675,288258450, 1006)
(215231234,176268960, 1007)
(76890032,900303770, 1008 )
(765398753,704099635, 1004 )





Viewing all articles
Browse latest Browse all 23857

Trending Articles



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