简体   繁体   中英

Populate auto-increment INT 5 digit value in case of null in SQL Server

I have a scenario where I need to auto generate the value of a column if it is null.

Ex: employeeDetails :

empName empId  empExtension
  A      101   null
  B      102   987
  C      103   986
  D      104   null
  E      105   null

employeeDepartment :

deptName  empId   
   HR      101
   ADMIN   102
   IT      103
   IT      104
   IT      105

Query

SELECT 
    empdt.empId, empdprt.deptName, empdt.empExtension 
FROM 
    employeeDetails empdt
LEFT JOIN 
    employeeDepartment empdprt ON empdt.empId = empdprt.empId

Output:

empId deptName empExtension
 101    HR          null
 102    ADMIN       987
 103    IT          986
 104    IT          null
 105    IT          null

Now my question is I want to insert some dummy value which replaces null and auto-increments starting from a 5 digit INT number

Expected output:

empId     deptName    empExtension
 101    HR          12345
 102    ADMIN       987
 103    IT          986
 104    IT          12346
 105    IT          12347

Constraints : I cannot change existing tables structure or any column's datatypes.

You should be able to do that with a CTE to grab ROW_NUMBER , and then COALESCE to only use that number where the value is NULL:

WITH cte AS(
  SELECT empId, empExtension, ROW_NUMBER() OVER(ORDER BY empExtension, empId) rn
  FROM employeeDetails
)
SELECT cte.empId, deptName, COALESCE(empExtension, rn + 12344) empExtension
FROM cte LEFT JOIN employeeDepartment
  ON cte.empID = employeeDepartment.empID
ORDER BY cte.empId

Here's an SQLFiddle .

If you just want to create a unique random 5 digit number for those empExtension column values are null, then

Query

;with cte as
(
    select rn = row_number() over
    (
        order by empId
    ),*
    from employeeDetails
)
select t1.empId,t2.deptName,
case when t1.empExtension is null 
then t1.rn + (convert(numeric(5,0),rand() * 20000) + 10000) 
else t1.empExtension end as empExtension
from cte t1
left join employeeDepartment t2
on t1.empId = t2.empId;

SQL Fiddle

 declare @rand int = (rand()* 12345);
SELECT empdt.empId, empdprt.deptName, 
        isnull(empdt.empExtension,row_number() over(order by empdt.empId)+@rand)
   FROM employeeDetails empdt
LEFT JOIN employeeDepartment empdprt
   ON empdt.empId = empdprt.empId

Incase the empExtension, get the row_number + a random number.

Just an idea, can you save result of that query into temp table

SELECT empdt.empId, empdprt.deptName, empdt.empExtension
INTO #TempEmployee
FROM employeeDetails empdt
LEFT JOIN employeeDepartment empdprt
ON empdt.empId = empdprt.empId

And after that just do the update of #TempEmployee?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM