如何将此Oracle存储过程转换为SQL Server存储过程?

4smxwvx5  于 2023-11-17  发布在  Oracle
关注(0)|答案(2)|浏览(156)

我有一个下面提到的Oracle存储过程,它获取一个逗号分隔的字符串参数作为输入,通过一个循环将其拆分,并返回从拆分CSV中获得的ID的路径。我如何在SQL Server中创建一个工作方式相同的过程?

create or replace PROCEDURE FILE_LOOP(V_FID IN varchar2,
                                      V_NAME OUT VARCHAR2) IS
BEGIN
  FOR ITEM IN (SELECT  V.PATHH||'\'|| V.NAME AS PATH 
               FROM  FILES T INNER JOIN 
                     Table2 V ON T.FOLID=V.ID 
               WHERE T.ID IN (SELECT TRIM(REGEXP_SUBSTR(V_FID,'[^,]+', 1, LEVEL))
                              FROM DUAL
                              CONNECT BY LEVEL <= 1+ REGEXP_COUNT(V_FID , ',')))
  LOOP
     v_name:=v_name||item.PATH;
  END LOOP;

END;

字符串
请帮我写一个过程,使完全相同的输出在sql server?我是新的sql server。

waxmsbnn

waxmsbnn1#

我想这就是你想要的:

if object_id('FILE_LOOP', 'P') is not null
  drop procedure FILE_LOOP;
go

create PROCEDURE 
  FILE_LOOP(
  @V_FID varchar(4000),
  @V_NAME VARCHAR(4000) OUT) AS
  BEGIN
  SET NOCOUNT ON;
   DECLARE ITEM CURSOR FOR
   SELECT 
   ISNULL(V.PATHH, '') + '' +
   ISNULL(V.NAME, '') AS PATH 
   FROM 
   FILES T 
   INNER JOIN Table2 V ON T.FOLID=V.ID 
   WHERE T.ID IN( SELECT 
      RTRIM(LTRIM(REGEXP_SUBSTR(@V_FID ,'[^,]+', 1, LEVEL));
      FROM DUAL 
      CONNECT BY LEVEL <= 1 + REGEXP_COUNT(@V_FID ,',')))
  WHILE 1=1 
  BEGIN
  set @v_name=isnull(@V_NAME, '') + ISNULL(item.PATH, '');
  END;

 FETCH ITEM INTO;
 END;
 CLOSE ITEM;
 DEALLOCATE ITEM;

字符串

f0ofjuux

f0ofjuux2#

将此过程从Oracle转换到SQL Server的一种方法是使用游标:

CREATE or alter PROCEDURE FILE_LOOP
    @V_FID NVARCHAR(MAX),
    @V_NAME NVARCHAR(MAX) OUTPUT
AS
BEGIN
    DECLARE @Item NVARCHAR(MAX);
    DECLARE cur CURSOR FOR
        SELECT TRIM(value) AS ID
        FROM STRING_SPLIT(@V_FID, ',');

    SET @V_NAME = '';

    OPEN cur;
    FETCH NEXT FROM cur INTO @Item;

    WHILE @@FETCH_STATUS = 0
    BEGIN
        SELECT @V_NAME = @V_NAME + ' ' + V.PATHH + '\' + V.NAME
        FROM FILES T
        INNER JOIN Table2 V ON T.FOLID = V.ID
        WHERE T.ID = @Item;

        FETCH NEXT FROM cur INTO @Item;
    END;

    CLOSE cur;
    DEALLOCATE cur;
END;

字符串
您可以通过以下方式执行该过程:

DECLARE @OutputName NVARCHAR(MAX);
EXEC FILE_LOOP @V_FID ='11,22,33,444,98', @V_NAME = @OutputName OUTPUT;
SELECT @OutputName AS Result;


希望它能帮助

相关问题