W
W
White_Bambie2020-12-03 12:59:26
MySQL
White_Bambie, 2020-12-03 12:59:26

How to parametrize a query using an array (WHERE field IN (...)?

"SELECT * FROM testimony WHERE Name IN('" + "Record 1" + "','"+ "Record 2" + "')" works. How to make the values ​​loaded from an array (array)?
The array itself:
string[] array = new string[] { "Record 1", "Record 2" };

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Bannikov, 2020-12-03
@White_Bambie

https://stackoverflow.com/questions/2377506/pass-a...

P
Peter, 2020-12-03
@petermzg

Create a type in the database

CREATE TYPE [dbo].[TableValueType] AS TABLE(
  [value] varchar(50) NOT NULL
)

Then in code
var tableParam = new SqlParameter("@paramName", SqlDbType.Structured);
tableParam.TypeName = "[dbo].[TableValueType]";
tableParam.Direction = ParameterDirection.Input;
// Установка значений
var rows = new List<SqlDataRecord>();
var sqlMetaData = new SqlMetaData("value", SqlDbType.VarChar);
foreach (var value in values)
{
      var row = new SqlDataRecord(sqlMetaData);
      row.SetValues(value);
      rows.Add(row);
}
tableParam.Value = rows;

And the request will look like
SELECT * FROM testimony WHERE Name IN (select [value] from @paramName)

PS: Oops! The tag turns out to be MySql, and this solution is for MSSQL

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question