如何循环在SQLServer中动态创建的查询

5jvtdoz2  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(367)

我有一个存储过程,从表中获取数据库名称,然后尝试从该数据库名称创建一个动态查询并获取结果。一旦获取了结果,我需要循环这些结果,以便执行进一步的查询以获得所需的结果

USE DATABASE1
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [User].[update_client_details] 
AS
    DECLARE @clientdata CURSOR,
            @clientid INT,
            @SQL NVARCHAR(2000),
            @uid INT,
            @isFirst INT,
            @isTemp INT,
            @inactive INT,
            @createdDate Date

BEGIN
    DECLARE C CURSOR LOCAL FOR 
        SELECT clientuserid FROM USER.queen_client

    OPEN C
    FETCH NEXT FROM C INTO @clientid

    WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @SQL = N'SELECT userid, @isFirst=isfirst, @isTemp=istemp, @inactive=inactive, @createdDate=createddate FROM ' +QUOTENAME(@clientid)+'.USER.queen_user;';

        EXEC sys.sp_executesql @SQL, N'@inactive int OUTPUT, @uid int OUTPUT, @isFirst int OUTPUT, @isTemp int OUTPUT, @createdDate date OUTPUT', @inactive OUTPUT, @uid OUTPUT, @isFirst OUTPUT, @isTemp OUTPUT, @createdDate OUTPUT;

        // @SQL returns multiple rows - I need to loop the output of @SQL 
        // UPDATE QUERY BASED ON IF CONDITION COMES HERE

        FETCH NEXT FROM C INTO @clientid
    END

    CLOSE C
    DEALLOCATE C
END

由于sql查询是动态的-如何循环此动态查询的输出。

sf6xfgos

sf6xfgos1#

因为sql查询是动态的,所以如何循环这个动态查询的输出。
在动态查询外部创建一个临时表,并将其插入到动态查询中。然后你可以从临时表中读取。

SET @SQL = N'
INSERT INTO #tempUser(userId,IsFirst,IsTemp,inactive,createddate)
SELECT userid, isfirst, istemp, inactive, createddate 
FROM ' +QUOTENAME(@clientid)+'.USER.queen_user;';

但更好的总体方法可能是在所有表的单独数据库中创建分区视图。如

create view queen_user
as
select 123 clientId, userid, isfirst, istemp, inactive
from Client123.USER.queen_user
union all
select 124 clientId, userid, isfirst, istemp, inactive
from Client124.USER.queen_user
union all
. . .
union all
select 999 clientId, userid, isfirst, istemp, inactive
from Client999.USER.queen_user

并有一个过程,可以在添加新的客户机数据库时随时对其进行更改。

相关问题