使用“IN” SQL函数中的值将.NET中的逗号分隔值传递给存储过程,可以通过以下步骤实现:
string values = "1,2,3,4,5";
string[] valueArray = values.Split(',');
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("myStoredProcedure", connection))
{
command.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = new SqlParameter("@values", SqlDbType.Structured);
parameter.Value = valueArray;
parameter.TypeName = "dbo.MyTableType";
command.Parameters.Add(parameter);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// Process the results
}
}
}
}
CREATE TYPE dbo.MyTableType AS TABLE (
Value INT
)
CREATE PROCEDURE myStoredProcedure
@values dbo.MyTableType READONLY
AS
BEGIN
SELECT * FROM MyTable WHERE Value IN (SELECT Value FROM @values)
END
这样,就可以将.NET中的逗号分隔值传递给存储过程,并在存储过程中使用“IN” SQL函数来查询数据。
领取专属 10元无门槛券
手把手带您无忧上云