使用数字字符串作为 SQL 参数,使用 IN 运算符进行 SQL 查询资源



我正在尝试传递一个字符串p_strIds,其中的数字值由","分隔:

2844099,2844100,2844101,2844102,2844103,2844104,2844105,2844106,2844107,2844108,2844109,2844110,2844111,2844112,2844113,2844114,2844115,2844116,2844117,2844118该字符串用作 SqlParameter:

mySqlCommand.Parameters.Add(new SqlParameter("@p_Ids", p_strValores));

供 IN 运算符中的以下资源(添加为资源(查询使用:

UPDATE tbl_Datos 
SET col_Leyenda = (select col_Id from tbl_Leyenda where col_Leyenda = 'T') 
WHERE col_Id in (@p_Ids)

查询和 IN 运算符的结尾应如下所示:

UPDATE tbl_Datos 
SET col_Leyenda = (select col_Id from tbl_Leyenda where col_Leyenda = 'T') 
WHERE col_Id in (2844099,2844100,2844101,2844102,2844103,2844104,2844105,2844106,2844107,2844108,2844109,2844110,2844111,2844112,2844113,2844114,2844115,2844116,2844117,2844118)

但它说它无法将 nvarchar 转换为 int,我如何格式化要在 IN(...唰...

如果我将参数p_strIds与字符串一起使用,它可以工作。Format(queryString, p_strIds( 像这样:

queryString = UPDATE tbl_Datos SET col_Leyenda = (select col_Id from tbl_Leyenda where col_Leyenda = 'T') WHERE col_Id in ({0})
strSql = string.Format(queryString, p_strValores)
mySqlCommand = new SqlCommand(strSql, m_obSqlConnection);

关于如何在第一种方法中使用SQL语句作为资源的任何想法?

谢谢

表tbl_Leyenda 中tbl_Datos或col_Leyenda上的col_Id列声明为 NVARCHAR 数据类型。该列中可能有数据,其中至少包含一些非数字字符。

当 SQL 尝试运行 WHERE 语句时:WHERE col_Id in (@Ids)

它无法将 col_Id 中的非数字数据转换为假定为整数的@Ids中的数据列表。

您可以通过在列表中的每个 Id 两边加上单引号来解决此问题。它看起来更像这样:

'2844099','2844100','2844101','2844102','2844103','2844104','2844105','2844106','2844107','2844108','2844109','2844110','2844111','2844112','2844113','2844114','2844115','2844116','2844117','2844118'

也可能是变量@p_Leyenda作为整数值传入。您也应该尝试将其强制为字符串。与上面的col_Ids列表类似。

这里需要的是一个拆分函数。

创建拆分函数,如下所示

CREATE FUNCTION [dbo].[SplitString]
(
@sString nvarchar(2048),
@cDelimiter nchar(1)
)
RETURNS @tParts TABLE ( part nvarchar(2048) )
AS
BEGIN
if @sString is null return
declare @iStart int,
@iPos int
if substring( @sString, 1, 1 ) = @cDelimiter 
begin
set @iStart = 2
insert into @tParts
values( null )
end
else 
set @iStart = 1
while 1=1
begin
set @iPos = charindex( @cDelimiter, @sString, @iStart )
if @iPos = 0
set @iPos = len( @sString )+1
if @iPos - @iStart > 0          
insert into @tParts
values  ( substring( @sString, @iStart, @iPos-@iStart ))
else
insert into @tParts
values( null )
set @iStart = @iPos+1
if @iStart > len( @sString ) 
break
end
RETURN
END

然后,您更改查询,如下所示:

UPDATE tbl_Datos 
SET col_Leyenda = (select col_Id from tbl_Leyenda where col_Leyenda = 'T') 
WHERE col_Id in (Select part from SplitString(@p_Leyenda,','))

最后,唯一的方法是将字符串转换为列表:

List<string> p_Ids= p_strValores.Split(',').ToList();

然后将列表中的每个值转换为 int 并将它们添加到 aux List 中,例如 aux_p_Ids,然后在 sql 查询中使用它:

UPDATE tbl_Datos SET col_Leyenda = (select col_Id from tbl_Leyenda where col_Leyenda = @p_Leyenda) WHERE col_Id in aux_p_Ids

最新更新