数据库
首页 > 数据库> > sqlserver sql 循环

sqlserver sql 循环

作者:互联网

 通过临时表进行sql循环

-----------创建临时表--------------

SELECT * INTO #tempfensitocity
FROM(

SELECT * FROM dbo.Swb_Jc_FenGongSi fs WHERE
NOT EXISTS
(
SELECT * FROM dbo.Swb_Jc_FenGongSi AS A INNER JOIN dbo.Swb_Electronic_City AS B
ON A.FenGongSiID=B.FengGongSiID WHERE fs.FenGongSiID=B.FengGongSiID

)
) AS A

DECLARE @fengongsiid INT
DECLARE @chengshiid INT
DECLARE @parentid INT
DECLARE @iscity int
DECLARE @isjoin INT
DECLARE @cityid INT
DECLARE @cityname VARCHAR(100)

BEGIN TRANSACTION
BEGIN TRY
---循环插入----

WHILE EXISTS (SELECT 1 FROM #tempfensitocity)
BEGIN
set @parentid =NULL
SET @cityid=null
------拿到一条分公司id-------
SELECT TOP 1 @fengongsiid=FenGongSiID,@cityname=GongSiMingCheng,@iscity= CASE when IsCity=1 THEN 1 ELSE
0 end,@isjoin=IsJoin FROM #tempfensitocity
--------取得对应的@parentid-----------------
SELECT @parentid=A.FenGongSiID FROM dbo.Swb_Jc_FenGongSi AS A WHERE EXISTS
(
SELECT 1 FROM dbo.Swb_Jc_FenGongSi AS B WHERE B.FenGongSiID=@fengongsiid AND
B.NewCityName=A.GongSiMingCheng
)

---------取得cityid--------------------
IF(@parentid IS null)
SELECT @cityid= MAX(CityID)+1 FROM Swb_Electronic_City
ELSE
SELECT @cityid=CityID FROM Swb_Electronic_City WHERE FengGongSiID=@parentid

IF(@cityid IS null)
SELECT @cityid= MAX(CityID)+1 FROM Swb_Electronic_City

---------取得城市id------------
SELECT @chengshiid= MAX(ChengShiID)+1 FROM Swb_Electronic_City

INSERT INTO dbo.Swb_Electronic_City(
ChengShiID,CityName,FengGongSiID,CityID,ParentID,IsCity,IsJoin,IsEnable
,ExtendType,CreatDate)
VALUES
(
@chengshiid,@cityname,@fengongsiid,@cityid,@parentid,@iscity,@isjoin,NULL,1,GETDATE()

)

DELETE #tempfensitocity WHERE FenGongSiID=@fengongsiid
END

END TRY
BEGIN CATCH
if(@@trancount>0)

ROLLBACK TRANSACTION

END CATCH
if(@@trancount>0)
COMMIT

-----删除临时表--------
DROP TABLE #tempfensitocity

END

标签:dbo,Swb,sqlserver,parentid,cityid,循环,sql,DECLARE,SELECT
来源: https://www.cnblogs.com/gfbppy/p/10422061.html