在准备好的语句中使用游标进行更新

时间:2018-08-05 23:08:45

标签: java sql-server jdbc cursor prepared-statement

我在JDBC准备的语句中使用以下游标,如下所示:

DECLARE c CURSOR GLOBAL FORWARD_ONLY DYNAMIC SCROLL_LOCKS TYPE_WARNING 
FOR 
SELECT TxtPtr = TEXTPTR(PT.BODY), Src = N'ReplaceString', 
Offset = PATINDEX(N'%[^A-Za-z0-9]SearchThis[^A-Za-z0-9]%', PT.BODY) 
FROM       dbo.BODYCONTENT AS PT    
WHERE       PT.BODY LIKE N'%[^A-Za-z0-9]SearchThis[^A-Za-z0-9]%';
OPEN c;
DECLARE @Ptr binary(16), @Src nvarchar(50), @Offset integer;
FETCH NEXT FROM c INTO @Ptr, @Src, @Offset;
WHILE @@FETCH_STATUS=0
BEGIN;
BEGIN TRANSACTION;
UPDATE dbo.BODYCONTENT SET BODY = ltrim(rtrim(replace
(replace(replace(N' ' + cast(BODY as nvarchar(max)) + N' ','    
','<>'),'>' + @Offset + '<','>' + @Src+ '<'),'<>',' '))) 
from dbo.BODYCONTENT
COMMIT TRANSACTION;
FETCH NEXT FROM c INTO @Ptr, @Src, @Offset;
END;CLOSE c; DEALLOCATE c;

当我直接在数据库中执行上述游标时,只有将@Src@Offset的值显式指定为'>SearchThis<','>ReplaceString<'时,它才起作用

如何在查询中使用@Src@Offset

JDBC准备语句:

String sql3 = "DECLARE c CURSOR GLOBAL FORWARD_ONLY DYNAMIC 
                SCROLL_LOCKS TYPE_WARNING FOR" +    
              " SELECT TxtPtr = TEXTPTR(PT.BODY), Src = N'+ ? + ', 
               Offset = PATINDEX(N'%[^A-Za-z0-9] + ? + [^A-Za-z0-9]%', PT.BODY)" +
               " FROM dbo.BODYCONTENT AS PT" + 
               " WHERE PT.BODY LIKE N'%[^A-Za-z0-9]?[^A-Za-z0-9]%';" + 
               " OPEN c;" + 
               " DECLARE @Ptr binary(16), @Src nvarchar(50), @Offset    
                  integer;" + 
               " FETCH NEXT FROM c INTO @Ptr, @Src, @Offset;" + 
               " WHILE @@FETCH_STATUS=0" + 
               " BEGIN" + 
               " BEGIN TRANSACTION;" + 
               " UPDATE dbo.BODYCONTENT SET BODY = ltrim(rtrim(replace(replace(replace(N' ' + cast(BODY as nvarchar(max)) + N' ',' ','<>'),'>' + @Offset +'<','>' + @Src + '<'),'<>',' '))) from dbo.BODYCONTENT" + 
        "COMMIT TRANSACTION;" + 
        "FETCH NEXT FROM c INTO @Ptr, @Src, @Offset;" + 
        "END;CLOSE c; DEALLOCATE c;";



pstmt = conn.prepareStatement(sql3);



            pstmt.setNString(1, searchStr);
            pstmt.setNString(2, replaceString);
            pstmt.setNString(3, searchStr);


            pstmt.executeUpdate();

我应该如何实现呢?

我想的问题是,我给?设置了setNString要设置的参数。游标本身没有问题,游标可以与硬编码值一起正常工作。但是我希望能够使用setNString或类似的东西从配置文件中传递Java应用程序中的参数。

1 个答案:

答案 0 :(得分:0)

无需尝试理解所有patindex并替换字符串(因为我的大脑爆炸了),它应该是一个简单的无游标更新语句,如下所示:

UPDATE dbo.BODYCONTENT SET BODY = ltrim(rtrim(replace
(replace(replace(N' ' + cast(BODY as nvarchar(max)) + N' ','    
','<>'),'>' + PATINDEX(N'%[^A-Za-z0-9]SearchThis[^A-Za-z0-9]%', PT.BODY)  + '<','>' + N'ReplaceString'+ '<'),'<>',' '))) 
from dbo.BODYCONTENT
WHERE PT.BODY LIKE N'%[^A-Za-z0-9]SearchThis[^A-Za-z0-9]%';