2015-08-26 84 views
1

在我的SQL我有這個疑問,我想增加ID與此插入具有增量ID

我不想使用identity(1,1)

INSERT INTO dbo.tbl_waredetails 
     (wd_id, wd_mt_code, wd_wa_Id, wd_supply, wd_description, wd_status) 
    SELECT  
     (SELECT ISNULL(MAX(wd.wd_id), 0) + 1 
     FROM dbo.tbl_waredetails AS wd), 
     dbo.tbl_material.mat_code, @id, 
     dbo.fun_CompRem(mat_code, -1, @user_id) AS supply, 
     NULL, 0 
    FROM     
     tbl_material 
    INNER JOIN 
     dbo.tbl_MatUnit ON dbo.tbl_material.mat_MatUnt_Code = dbo.tbl_MatUnit.Matunt_code 
    INNER JOIN 
     dbo.tbl_MatGroup ON dbo.tbl_material.mat_MatGrp_Code = dbo.tbl_MatGroup.MatGrp_Code 

但它總是發2作爲ID

+2

使用'IDENTITY'是做到這一點的最好也是最可靠的方法 - 爲什麼從一開始就排除它?手動執行的任何操作**都不容易出現併發安全問題,例如產生重複值 –

回答

1

試試下面的查詢

INSERT INTO dbo.tbl_waredetails 
     (wd_id, wd_mt_code, wd_wa_Id, wd_supply, wd_description, wd_status) 
    SELECT  
     (SELECT ISNULL(MAX(wd.wd_id), 0) 
     FROM dbo.tbl_waredetails AS wd)+ (row_number() over (order by wd.wd_id)), 
     dbo.tbl_material.mat_code, @id,  
     dbo.fun_CompRem(mat_code, -1, @user_id) AS supply, 
     NULL, 0 
    FROM     
     tbl_material 
    INNER JOIN 
     dbo.tbl_MatUnit ON dbo.tbl_material.mat_MatUnt_Code = dbo.tbl_MatUnit.Matunt_code 
    INNER JOIN 
     dbo.tbl_MatGroup ON dbo.tbl_material.mat_MatGrp_Code = dbo.tbl_MatGroup.MatGrp_Code 
+1

這是一種明顯的,簡單的方法 - 對於真實生活場景太簡單了,但是,因爲如果多個客戶端同時執行此代碼,將會創建** duplicate *'wd_id'值。 –

+0

它有這個錯誤,因爲它不包含在聚合函數或GROUP BY子句和用戶這個查詢中,但返回null SELECT ISNULL(MAX(wd.wd_id),0)+(row_number()over(order by wd。 wd_id)) FROM dbo.tbl_waredetails AS wd \t \t GROUP BY wd.wd_id – aliyousefian

+0

請再次檢查 –

0
with cte as 
(select (SELECT isnull(MAX(wd.wd_id),0) FROM dbo.tbl_waredetails) as iden,dbo.tbl_material.mat_code,@id,  


      dbo.fun_CompRem(mat_code,-1,@user_id 
      )as supply,NULL,0 
      FROM  tbl_material INNER JOIN 
            dbo.tbl_MatUnit ON dbo.tbl_material.mat_MatUnt_Code = dbo.tbl_MatUnit.Matunt_code INNER JOIN 
            dbo.tbl_MatGroup ON dbo.tbl_material.mat_MatGrp_Code = dbo.tbl_MatGroup.MatGrp_Code 
where ROW_NUMBER () 
    OVER (order by 1)=1 

union all 

select c.iden+1,dbo.tbl_material.mat_code,@id,  


      dbo.fun_CompRem(mat_code,-1,@user_id 
      )as supply,NULL,0 
      FROM  tbl_material INNER JOIN 
            dbo.tbl_MatUnit ON dbo.tbl_material.mat_MatUnt_Code = dbo.tbl_MatUnit.Matunt_code INNER JOIN 
            dbo.tbl_MatGroup ON dbo.tbl_material.mat_MatGrp_Code = dbo.tbl_MatGroup.MatGrp_Code 
join cte as d on 1=1 
where ROW_NUMBER () 
    OVER (order by 1)!=1 

) 




INSERT INTO dbo.tbl_waredetails 
     ( 
      wd_id, 
      wd_mt_code , 
      wd_wa_Id , 
      wd_supply , 
      wd_description , 
      wd_status 
     ) 

    SELECT iden, dbo.tbl_material.mat_code,@id,supply,NULL,0 
      FROM    CTE