在SQL Server中使用光标的循环的动态SQL通过表行通过表行

发布于 2025-01-17 13:48:25 字数 2298 浏览 1 评论 0原文

我有两个表(#AAA_TEST& #bbb_test)。我想循环遍历#AAA_TEST表的每一行。

我需要使用光标迭代#AAA_TEST的每一行。另外,我在存储过程中创建了一个动态的SQL语句。我想一起使用动态SQL和光标来生成我的最终查询。 我很难找到解决此问题的正确方法。

这是我所做的。

这是我的两个表:

DROP TABLE IF EXISTS #aaa_Test;

CREATE TABLE #aaa_Test 
(
    [Columnname] VARCHAR(500) NOT NULL,
    [Length] VARCHAR (500) NOT NULL
);

INSERT INTO #aaa_Test
VALUES ('Hole', '18'), ('Project', '8'), ('Source', '10');

SELECT * FROM #aaa_Test;

DROP TABLE IF EXISTS #bbb_Test;

CREATE TABLE #bbb_Test 
(
    [Hole] VARCHAR(500) NOT NULL,
    [Project] VARCHAR (500) NOT NULL,
    [source] VARCHAR (500) NOT NULL
);

INSERT INTO #bbb_Test
VALUES ('08SWRB001', 'WDW', 'Droll'),
       ('08SWRB002', 'WDWWDW', 'Gup'),
       ('08SWRB003', 'WDWMD', 'Sh');

SELECT * FROM #bbb_Test;

这是我想要的最终选择查询(所需的结果),但是我想要动态,因为我在#AAA*test的列名中有1000多个条目。*如果您仔细查看以下查询,孔,项目和源来自#AAA_Test表的列名。我希望此列名称动态而不是硬编码每个列名称,因为我在#AAA test Table 中具有许多列名的条目。

SELECT 
    CONCAT(Hole, SPACE((SELECT [Length] FROM #aaa_Test 
                        WHERE columnname = 'Hole') - LEN(Hole))) AS Hole,
    CONCAT(Project, SPACE((SELECT [Length] FROM #aaa_Test 
                           WHERE columnname='Project') - LEN(project))) AS project,
    CONCAT([Source], SPACE((SELECT [Length] FROM #aaa_Test 
                            WHERE columnname='Source') - LEN([source]))) AS [source]
FROM 
    #bbb_Test;

这是我的动态SQL和光标的组合:

DECLARE @MyCursor CURSOR;
DECLARE @MyField YourFieldDataType;

BEGIN
    SET @MyCursor = CURSOR FOR
        SELECT * FROM #aaa_Test as a;     

    OPEN @MyCursor; 

    FETCH NEXT FROM @MyCursor INTO @MyField;

    WHILE @@FETCH_STATUS = 0
    BEGIN
        DECLARE @SQL VARCHAR(MAX);

        SET @SQL = '';

        SELECT @SQL = @SQL + ' SELECT Concat(' + QUOTENAME(a.[Columnname], '') + ',SPACE((SELECT [Length] from #aaa_Test where columnname = '+ QUOTENAME(a.[columnname], '''') +'-LEN(' + QUOTENAME(a.[Columnname],'') +' as '+ QUOTENAME(a.[Columnname],'')    
        FROM #bbb_Test AS b;

        PRINT @SQL; 
  
        FETCH NEXT FROM @MyCursor INTO @MyField; 
    END; 

    EXEC(@SQL);

    CLOSE @MyCursor;
    DEALLOCATE @MyCursor;
END;

I have two tables (#aaa_Test & #bbb_Test). I want to loop through each row of the #aaa_Test table.

I need to iterate every row of #aaa_Test using a cursor. Also, I have a dynamic SQL statement I've created in a stored procedure. I want to use dynamic SQL and cursor both together to generate my final query.
I'm having a hard time figuring out the right way to approach this problem.

Here's what I have done.

These are my two tables:

DROP TABLE IF EXISTS #aaa_Test;

CREATE TABLE #aaa_Test 
(
    [Columnname] VARCHAR(500) NOT NULL,
    [Length] VARCHAR (500) NOT NULL
);

INSERT INTO #aaa_Test
VALUES ('Hole', '18'), ('Project', '8'), ('Source', '10');

SELECT * FROM #aaa_Test;

DROP TABLE IF EXISTS #bbb_Test;

CREATE TABLE #bbb_Test 
(
    [Hole] VARCHAR(500) NOT NULL,
    [Project] VARCHAR (500) NOT NULL,
    [source] VARCHAR (500) NOT NULL
);

INSERT INTO #bbb_Test
VALUES ('08SWRB001', 'WDW', 'Droll'),
       ('08SWRB002', 'WDWWDW', 'Gup'),
       ('08SWRB003', 'WDWMD', 'Sh');

SELECT * FROM #bbb_Test;

This is my final select query that I want in output(Desired Result) but I wanted dynamic as I have more than 1000 entries of column name for #aaa*Test.* If you look at the below query closely, Hole, Project and source come from column name of #aaa_test table. I want this column name dynamic rather than hard coding each column name as I have so many entries of column name in #aaaTest table .

SELECT 
    CONCAT(Hole, SPACE((SELECT [Length] FROM #aaa_Test 
                        WHERE columnname = 'Hole') - LEN(Hole))) AS Hole,
    CONCAT(Project, SPACE((SELECT [Length] FROM #aaa_Test 
                           WHERE columnname='Project') - LEN(project))) AS project,
    CONCAT([Source], SPACE((SELECT [Length] FROM #aaa_Test 
                            WHERE columnname='Source') - LEN([source]))) AS [source]
FROM 
    #bbb_Test;

This is the combination of my dynamic SQL and cursor:

DECLARE @MyCursor CURSOR;
DECLARE @MyField YourFieldDataType;

BEGIN
    SET @MyCursor = CURSOR FOR
        SELECT * FROM #aaa_Test as a;     

    OPEN @MyCursor; 

    FETCH NEXT FROM @MyCursor INTO @MyField;

    WHILE @@FETCH_STATUS = 0
    BEGIN
        DECLARE @SQL VARCHAR(MAX);

        SET @SQL = '';

        SELECT @SQL = @SQL + ' SELECT Concat(' + QUOTENAME(a.[Columnname], '') + ',SPACE((SELECT [Length] from #aaa_Test where columnname = '+ QUOTENAME(a.[columnname], '''') +'-LEN(' + QUOTENAME(a.[Columnname],'') +' as '+ QUOTENAME(a.[Columnname],'')    
        FROM #bbb_Test AS b;

        PRINT @SQL; 
  
        FETCH NEXT FROM @MyCursor INTO @MyField; 
    END; 

    EXEC(@SQL);

    CLOSE @MyCursor;
    DEALLOCATE @MyCursor;
END;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不醒的梦 2025-01-24 13:48:26

您不需要光标,并且由于您是从#AAA_TEST构建查询,要么:

DECLARE @sql nvarchar(max) = N'SELECT ';

SELECT @sql += STRING_AGG(CONVERT
(
  nvarchar(max), 
  CONCAT
  (
    char(13), char(10),
    'CONCAT(',
    QUOTENAME(Columnname), 
    ',SPACE(',
    CONVERT(varchar(11), [Length]),
    '-LEN(', 
    QUOTENAME(Columnname), 
    '))) AS ',
    QUOTENAME(Columnname)
  )
), ',')
FROM #aaa_Test;

SET @sql += char(13) + char(10) + N' FROM #bbb_Test;';


SELECT @sql;

EXEC sys.sp_executesql @sql;

输出:

SELECT 
CONCAT([Hole],SPACE(18-LEN([Hole]))) AS [Hole],
CONCAT([Project],SPACE(8-LEN([Project]))) AS [Project],
CONCAT([Source],SPACE(10-LEN([Source]))) AS [Source]
FROM #bbb_Test;
项目来源
08SWRB001WDWDROLL
08SWRB002WDWWDWGUP
08SWRB003WDWMDSH

You don't need a cursor for this and, since you're building the query from #aaa_Test anyway, you don't need to pull the length from the #temp table as a subquery in every row, either:

DECLARE @sql nvarchar(max) = N'SELECT ';

SELECT @sql += STRING_AGG(CONVERT
(
  nvarchar(max), 
  CONCAT
  (
    char(13), char(10),
    'CONCAT(',
    QUOTENAME(Columnname), 
    ',SPACE(',
    CONVERT(varchar(11), [Length]),
    '-LEN(', 
    QUOTENAME(Columnname), 
    '))) AS ',
    QUOTENAME(Columnname)
  )
), ',')
FROM #aaa_Test;

SET @sql += char(13) + char(10) + N' FROM #bbb_Test;';


SELECT @sql;

EXEC sys.sp_executesql @sql;

Output:

SELECT 
CONCAT([Hole],SPACE(18-LEN([Hole]))) AS [Hole],
CONCAT([Project],SPACE(8-LEN([Project]))) AS [Project],
CONCAT([Source],SPACE(10-LEN([Source]))) AS [Source]
FROM #bbb_Test;
HoleProjectSource
08SWRB001WDWDroll
08SWRB002WDWWDWGup
08SWRB003WDWMDSh
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文