具有CAST功能的参数化更新查询

时间:2018-06-18 18:22:13

标签: sql sql-server prepared-statement parameterized-query

我正在使用更新查询,如下所示:

 UPDATE PeopleTable 
     SET firstname = CAST(REPLACE(CAST(firstname as nvarchar(max)), 'John', 'ReplacedFirstName') as ntext)

我想为几个名字做同样的事,比如“Dave,Tom,Harry,Rick,Nick”

我该如何正确地做到这一点?

我试过这样的事情:

 create procedure proc2
 @sp varchar(25)
 as
 select UPDATE PeopleTable SET first name = CAST(REPLACE(CAST(BODY as
       nvarchar(max)), searchString = @sp,'ReplacedFirstName') as ntext)
 go


 declare @sp varchar(25)

 //I want to loop here and execute the stored proc for a list of names
 set @sp = 'name'     
 exec proc2 @sp

2 个答案:

答案 0 :(得分:0)

您可以将cte与值构造

一起使用
with t as (
       select *
       from ( values ('John', 'ReplacedFirstName'), ('Dave', 'ReplacedFirstName'),
                      . . .
            ) tt (firstname, ReplacedFirstName)
 )

update p 
      set p.firstname = t.ReplacedFirstName
from PeopleTable p inner join
     t 
     on t.firstname = p.firstname;

答案 1 :(得分:0)

    PreparedStatement pstmt = null;

    String query = "UPDATE PeopleTable SET firstname = CAST(REPLACE(CAST(firstname as nvarchar(max)), ? ,'ReplacedFirstName') as ntext)";

    pstmt = conn.prepareStatement(query);
    for(String s: myList) {

    pstmt.setString(1, s);

    pstmt.addBatch();

    }

    pstmt.executeUpdate();