SQL Server存储过程/游标

时间:2014-02-05 20:56:43

标签: sql sql-server tsql

我有一个包含20个空间表(Zoom1-Zoom20)的列表,并且在这些表中弹出时间无效的几何图形。当出现无效几何体时,我运行以下语句来查找无效几何体的位置:

SELECT ID FROM Zoom10 WhERE Location.STIsValid() = 0

通常我必须为每个Zoom表运行上面的语句(导致无效几何的错误不指示哪个缩放表具有无效的几何),并且当从select语句返回结果时,我运行以下语句到纠正几何:

UPDATE MGeoZoom10 set Location = Location.MakeValid() where Location.STIsValid() = 0

我的问题是,这个过程可以通过获取缩放表列表的存储过程自动化

select name from sys.tables where name like '%zoom'

然后使用

循环缩放表
SELECT ID FROM Zoom10 WhERE Location.STIsValid() = 0

如果返回结果,它会在缩放表上运行update语句吗?

2 个答案:

答案 0 :(得分:1)

试试这个:

sp_msforeachtable '
if ''?'' Like ''%Zoom%'' 
    Begin
        If Exists(SELECT ID FROM ? WhERE Location.STIsValid() = 0)
            UPDATE ? set Location = Location.MakeValid() where Location.STIsValid() = 0
    End     
'

答案 1 :(得分:0)

你有2个名为STIsValid和MakeValid的UDF吗?如果是这样,你可以这样做......

    SELECT id INTO #Processed FROM Sysobjects WHERE name = '(no such table)'

    DECLARE @TableId int, @TableName varchar(255), @CorrectionSQL varchar(255)

    SELECT @TableId = MIN(id) FROM Sysobjects WHERE type = 'U' AND name LIKE '%zoom'
    AND id NOT IN (SELECT id FROM #Processed)

    SET @TableId = ISNULL(@TableId, -1)

    WHILE @TableId > -1 BEGIN

        PRINT @TableId

        SELECT @TableName = name FROM Sysobjects WHERE type = 'U' AND id = @TableId
        SET @CorrectionSQL = 'UPDATE ' + @TableName + ' SET Location = dbo.MakeValid(Location) where dbo.STIsValid(Location) = 0'

        PRINT @CorrectionSQL
        EXEC(@CorrectionSQL)


        INSERT INTO #Processed (id) VALUES(@TableId)

        SELECT @TableId = MIN(id) FROM Sysobjects WHERE type = 'U' AND name IN ('DimAccount', 'DimCurrency', 'DimCustomer')
            AND id NOT IN (SELECT id FROM #Processed)

    END