我想遍历数据集并将数据插入所需的位置,然后从临时表中选择所有行

时间:2019-01-22 15:15:51

标签: sql sql-server sql-server-2012

当前,我正在将所有非播放项插入临时表,然后插入所有播放项。取而代之的是,我想遍历数据集并在需要的地方插入,然后从临时表中选择所有行。

DECLARE @LEADWONDetail TABLE
(  
  SeqNo [int] IDENTITY(1,1) NOT NULL,
  Constituencyid INT,
  leadwoncode INT,
  [Status] NVARCHAR(100),
  DistName NVARCHAR(500),
  ConstName NVARCHAR(300),
  MandalName NVARCHAR(300),
  VillageName NVARCHAR(500),
  CandName NVARCHAR(500),
  Party NVARCHAR(200),
  Updatedtimestamp DATETIME
)

IF ((SELECT COUNT(*) FROM tbl_WB WHERE constid = @SlNo) = 0 AND @SlNo IS NOT  NULL)
BEGIN
    INSERT INTO tbl_WB 
    SELECT @SlNo
END


INSERT INTO @LEADWONDetail
SELECT A.Const_code AS CONST_CODE, A.Lead_WonCode,
(SELECT
 CASE A.Lead_WonCode
   WHEN '1' THEN N'LEAD'
   WHEN '100' THEN N'WON'
 END) AS [STATUS],R.English as DistrictName,OD.English as ConstName,D.English AS MandalName,A.English AS VillageName, B.English AS CANDINAME, C.English AS Party, A.UPDATEDDATETIME AS [DATETIME]
from tbl_ConstituencyMaster as A
LEFT OUTER JOIN tbl_CandidateMaster B ON A.Lead_CandiCode = B.Cand_Code
LEFT OUTER JOIN tbl_PartyMaster C ON B.PartyCode = C.PartyCode 
join tbl_DistrictMaster D on A.Dist_Code=D.Dist_Code 
join tbl_regionmaster R on a.reg_code=R.reg_code
join tbl_olddistrictMaster od on a.Old_dist_code=od.old_dist_code
AND A.STATECODE = @STATECODE and A.Lead_WonCode = 100 and A.Phase= 1 and R.English in ('ADILABAD','BHADRADRI  KOTHAGUDEM','JAGTIAL','JANGAON','JAYASHANKAR BHUPALPALLY','JOGULAMBA GADWALA','KAMAREDDY','KARIMNAGAR','KHAMMAM','KUMURAMBHEEM','MAHABUBABAD','MANCHERIAL','MEDAK','MEDCHAL','NAGARKURNOOL')
and A.Const_code not in (select distinct ConstId from tbl_WB)
ORDER BY A.UPDATEDDATETIME DESC

INSERT INTO @LEADWONDetail
SELECT A.Const_code AS CONST_CODE, A.Lead_WonCode,
(SELECT
 CASE A.Lead_WonCode
   WHEN '1' THEN N'LEAD'
   WHEN '100' THEN N'WON'
 END) AS [STATUS],R.English as DistrictName,OD.English as ConstName,D.English AS MandalName,A.English AS VillageName, B.English AS CANDINAME, C.English AS Party, A.UPDATEDDATETIME AS [DATETIME]
from tbl_ConstituencyMaster as A
LEFT OUTER JOIN tbl_CandidateMaster B ON A.Lead_CandiCode = B.Cand_Code
LEFT OUTER JOIN tbl_PartyMaster C ON B.PartyCode = C.PartyCode 
join tbl_DistrictMaster D on A.Dist_Code=D.Dist_Code 
join tbl_regionmaster R on a.reg_code=R.reg_code
join tbl_olddistrictMaster od on a.Old_dist_code=od.old_dist_code
AND A.STATECODE = @STATECODE and A.Lead_WonCode = 100 and A.Phase= 1 and R.English in ('ADILABAD','BHADRADRI  KOTHAGUDEM','JAGTIAL','JANGAON','JAYASHANKAR BHUPALPALLY','JOGULAMBA GADWALA','KAMAREDDY','KARIMNAGAR','KHAMMAM','KUMURAMBHEEM','MAHABUBABAD','MANCHERIAL','MEDAK','MEDCHAL','NAGARKURNOOL')
and A.Const_code in (select distinct ConstId from tbl_WB)
ORDER BY A.UPDATEDDATETIME DESC

select * from @LEADWONDetail

创建表tbl_WB(id int identity(1,1),ConstId INT)

在执行结果中,当前行的第三行是必需的。

1 个答案:

答案 0 :(得分:2)

如果在最终的SELECT上没有ORDER BY,则无法强制执行返回结果的顺序。

您可以在特定位置插入行并以无ORDER BY的方式返回它们的想法是谬论。