2015-10-06 31 views
0

我有一個場景,如果它爲空,我需要自動生成列的值。在SQL Server中填充自動遞增INT 5數字值的情況下

例: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 

查詢

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

輸出:

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

現在我的問題是我要插入一些虛擬值代替零和自動遞增,從5位數INT編號開始

預期輸出:

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

約束:我不能改變現有的表結構或任何列的數據類型。

回答

1

你應該能夠做到這一點的CTE搶ROW_NUMBER,然後COALESCE只使用數字,該值爲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 

這裏是一個SQLFiddle

+0

完美:)謝謝你一噸 –

0

只是一個想法,你可以保存查詢到臨時表

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

而這只是做#TempEmployee的更新後的結果呢?

1

如果你只是想爲那些empExtension列值的唯一的隨機5位數字爲空,那麼

查詢

;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

+0

嗨Ullas,你能幫我從12345等開始產生序列。 ? –

+0

非常感謝:)很棒 –

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

櫃面empExtension ,得到row_number +一個隨機數。

+0

簡單易懂:) great Osama Orabi –

相關問題