将(1,2,3,4)作为SqlParameter传递

时间:2016-12-28 10:09:11

标签: c# sql-server ado.net

我正在尝试传递这个动态生成的字符串(1,2,3,4),但我收到错误:

  

转换nvarchar值时转换失败' 1,2,3,4'至   数据类型int

如何解决此错误?

    public DataTable GetAll(int [] idArray)
    {
        DataTable dt = new DataTable();

        var paramNames =   Enumerable
                          .Range(0, idArray.Length)
                          .Select(index => $"@prm{index}")
                          .ToArray();
        string query = $"SELECT link FROM Test WHERE id IN ({string.Join(",", paramNames)}) ORDER BY seq.Sequence";

        try
        {
            using (SqlConnection conn = new SqlConnection(connStringUniApp))
            {
                conn.Open();
                using (SqlCommand command = new SqlCommand(query, conn))
                {
                    for (int i = 0; i < paramNames.Length; ++i)
                    {
                        command.Parameters.Add(new SqlParameter(paramNames[i], idArray[i]));
                    }

                    using (SqlDataReader rdr = command.ExecuteReader())
                    {
                        dt.Load(rdr);
                    }
                    command.Parameters.Clear();
                }
                return dt;
                Console.Write(dt);
            }
        }
        catch (Exception ex)
        {
            Console.Write(ex.ToString());
            return dt;
        }
    }

3 个答案:

答案 0 :(得分:1)

您必须生成许多参数:

string[] paramValues = parameterString.Split(',');

var paramNames = Enumerable
  .Range(0, paramValues.Length)
  .Select(index => $"@prm{index}")
  .ToArray();

string query = $"SELECT * from test WHERE testId IN ({string.Join(",", paramNames)})";

...

for (int i = 0; i < paramNames.Length; ++i)
  command.Parameters.Add(new SqlParameter(paramNames[i], paramValues[i]));

或者根本不使用参数并添加更容易实现但易于 SQL注入的字符串,这就是为什么不能被推荐:

string query = $"SELECT * from test WHERE testId IN ({ParameterString})";

答案 1 :(得分:0)

试试这个

command.Parameters.Add(new SqlParameter("@ParameterString", Convert.ToInt32(parameterString.ToString())));

答案 2 :(得分:0)

您可以在SQL Server中编写函数并调用该函数来拆分您的字符串参数并获取整数ID来检查条件。

string query = "SELECT * from test t join [dbo].[SplitStringByComma](@ParameterString, ',') s on  s.value = testId ORDER BY Id"

用逗号分割字符串的功能如下:

ALTER FUNCTION [dbo].[SplitStringByComma]  (    
@SplitString varchar(max),
@char char)
RETURNS @Values TABLE 
(
 value int
)
AS

begin
declare @CharPosition int
declare @SubString varchar(max)
set @SplitString = RTRIM(LTRIM(@SplitString))   
  if(len(@SplitString)>0 and CHARINDEX(@char,@SplitString)>0)
  begin
    while(CHARINDEX(@char,@SplitString)>0)
        begin
        set @CharPosition = CHARINDEX(@char,@SplitString)
        set @SubString= SUBSTRING(@SplitString,0,@CharPosition)
        if(len(@SubString)>0)
        insert into @Values
        select @SubString
        set @SplitString = SUBSTRING(@SplitString,@CharPosition+1,LEN(@SplitString))        
        end
        if(len(@SubString)>0)
        insert into @Values select @SplitString
   end
   else
        insert into @Values select @SplitString
return
end