• 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

  • 相关阅读:
    openstack生产要素
    None
    nginx优化 tbc
    zabbix开源监控解决方案
    HUGO & Hexo
    mysql数据库-运维合集
    Zabbix Agent ver5.0 批量部署
    CRI containerd
    zabbix聚合图形与Grafana图形展示
    zabbix 监控tomcat
  • 原文地址:https://www.cnblogs.com/gfbppy/p/10422061.html
Copyright © 2020-2023  润新知