14/02/2019 SqlServer: Parameterized Query With IN() Clause C# - CodeProject
SqlServer: Parameterized Query With IN() Clause C#
DiponRoy, 14 Feb 2019
A utility class to send parameters for IN() operator in SQL using parameterized queries
[Link] - 7.2 KB
Introduction
Using parameterized queries is simple
1. Create the SqlCommand command string with parameters.
2. Declare a SqlParameter object, assigning values as appropriate.
3. Assign the SqlParameter object to the SqlCommand object’s Parameters property.
But things get different when we have to work with IN() clause especially with an unknown number of objects or a list.
IN() Clause Helper
This class will help us to create both SQL string and SQL parameters
public class SqlServerInClauseParam<T>
{
public const char ParamIndicator = '@'; /*@paramName*/
public readonly string Prefix;
public const string Suffix = "Param";
public readonly SqlDbType DbDataType;
public readonly List<T> Data;
public SqlServerInClauseParam(SqlDbType dataType, List<T> data, string prefix = "")
{
Prefix = prefix;
DbDataType = dataType;
Data = data;
}
private string Name(int index)
{
var name = [Link]("{0}{1}{2}", Prefix, index, Suffix);
return name;
}
public string ParamsString()
{
string listString = "";
for (int i = 0; i < [Link]; i++)
{
if ()
{
[Link] 1/5
14/02/2019 SqlServer: Parameterized Query With IN() Clause C# - CodeProject
listString += ", ";
}
listString += [Link]("{0}{1}", ParamIndicator, Name(i));
}
return listString;
}
private List<SqlParameter> ParamList()
{
var paramList = new List<SqlParameter>();
for (int i = 0; i < [Link]; i++)
{
var data = new SqlParameter { ParameterName = Name(i), SqlDbType = DbDataType, Value =
Data[i] };
[Link](data);
}
return paramList;
}
public SqlParameter[] Params()
{
var paramList = ParamList();
return [Link]();
}
public SqlParameter[] Params(params SqlParameter[] additionalParameters)
{
var paramList = ParamList();
foreach (var param in additionalParameters)
{
[Link](param);
}
return [Link]();
}
}
ParamsString() will create parameter names string which will be added inside IN()
Params() will provide all the SqlPramter list for SQL command
We call also pass additional or existing SqlPramter's to Params()
SQL Query Build
/*data*/
byte isActive = 1;
List<string> emails = new List<string>()
{
"Jeff@[Link]",
"Tom@[Link]"
};
List<int> userTypes = new List<int>()
{
3, 4
};
/*IN() params*/
SqlServerInClauseParam<string> emailParam = new SqlServerInClauseParam<string>([Link],
emails, "email"); /*IN() clause param*/
SqlServerInClauseParam<int> userTypeParam = new SqlServerInClauseParam<int>([Link], userTypes,
"userType"); /*IN() clause param*/
/*regular param*/
SqlParameter isActiveParam = new SqlParameter("isActiveParam", [Link]) { Value = isActive };
/*regular param*/
/*sql*/
string sql = [Link](@"
SELECT *
FROM Employee
WHERE Email IN ({0})
[Link] 2/5
14/02/2019 SqlServer: Parameterized Query With IN() Clause C# - CodeProject
OR UserType IN ({1})
AND IsActive = @isActiveParam;",
[Link](), [Link]() /*using IN() clause param class*/
);
new SqlServerInClauseParam<string>([Link], emails, "email");
[Link] SQL data type
emails the actual data list
string data type of the list
"email" parameter name prefix, important if we are going to use multiple IN() clause in a single query
Parameterized Query With Entity Framework
List<SqlParameter> paramList = new List<SqlParameter>();
[Link]([Link]());
[Link]([Link]());
[Link](isActiveParam);
var db = new UmsSqlDbContext();
List<Employee> list = [Link]<Employee>(sql, [Link]()).ToList();
/*[Link]() is important*/
Passing additional SqlParameters to Params()
/*we can also do*/
//List<Employee> list = [Link]<Employee>(sql,
[Link]([Link](isActiveParam))).ToList();
Parameterized Query With SqlCommand
SqlConnection connection = new
SqlConnection([Link]["UmsDbContext"].ConnectionString);
[Link]();
SqlCommand command = new SqlCommand(sql, connection);
[Link]([Link]());
[Link]([Link]());
[Link](isActiveParam);
var reader = [Link]();
List<Employee> list = new List<Employee>();
while ([Link]())
{
[Link](new Employee
{
Id = Convert.ToInt32(reader["Id"]),
Name = reader["Name"].ToString(),
Email = reader["Email"].ToString(),
UserType = Convert.ToInt32(reader["UserType"]),
IsActive = [Link](reader["IsActive"])
});
}
[Link]();
Rather than creating a list, passing additional SqlParameters to Params()
/*we can also do*/
//[Link]([Link]([Link](isActiveParam)));
Data
[Link] 3/5
14/02/2019 SqlServer: Parameterized Query With IN() Clause C# - CodeProject
DB, Table & Data Rows
Find [Link] inside attached solution as bellow
USE [Ums]
GO
/****** Object: Table [dbo].[Employee] Script Date: 2/10/2019 [Link] AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Employee](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](100) NULL,
[Email] [varchar](100) NULL,
[UserType] [int] NULL,
[IsActive] [bit] NULL,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[Employee] ON
GO
INSERT [dbo].[Employee] ([Id], [Name], [Email], [UserType], [IsActive]) VALUES (1, N'Jeff',
N'Jeff@[Link]', 1, 1)
GO
INSERT [dbo].[Employee] ([Id], [Name], [Email], [UserType], [IsActive]) VALUES (2, N'Tom',
N'Tom@[Link]', 2, 1)
GO
INSERT [dbo].[Employee] ([Id], [Name], [Email], [UserType], [IsActive]) VALUES (3, N'Dan',
N'Dan@[Link]', 3, 1)
GO
INSERT [dbo].[Employee] ([Id], [Name], [Email], [UserType], [IsActive]) VALUES (4, N'Ban',
N'Ban@[Link]', 4, 1)
GO
SET IDENTITY_INSERT [dbo].[Employee] OFF
GO
Db Connection String
Change the DB connection at [Link] as needed
<connectionStrings>
<add name="UmsDbContext" connectionString="Server=L-156151377\SQLEXPRESS;Database=Ums;user
id=sa;password=pro@123;Integrated Security=false;" providerName="[Link]"/>
</connectionStrings>
Other Databases
If we need to do the same for other Databases, we only have to introduce a few modifications at
public const char ParamIndicator = '@'; /*@paramName*/
public readonly SqlDbType DbDataType;
Name(int index) method if needed
[Link] 4/5
14/02/2019 SqlServer: Parameterized Query With IN() Clause C# - CodeProject
About Download File
Find working Vs2017 console solution as the attachment. Create Db and change the connection string.
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
About the Author
DiponRoy No Biography provided
Bangladesh
Comments and Discussions
0 messages have been posted for this article Visit [Link]
Query-With-IN-Clause-Cshar to post and view comments on this article, or click here to get a print view with messages.
Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile Article Copyright 2019 by DiponRoy
Web01 | 2.8.190210.1 | Last Updated 14 Feb 2019 Everything else Copyright © CodeProject, 1999-2019
[Link] 5/5