I have two tables: AreaCode
and EquipmentNumber
.
+------------------------------------+
| AreaCd |
|---
Try this
SELECT Number, Type, Code FROM EqNum, AreaCd " +
"WHERE EqNum.AreaId = AreaCd.AreaId AND
isnull(Code,0) = " + int nCode + " or
isnull(Number,0) = '" + string sNumber + "' or isnull(Type,0) = '" + string sType + "'
SELECT e.Number, e.Type, a.Code
FROM EqNum e INNER JOIN AreaCd a
ON e.AreaId = a.AreaId
WHERE (@Number IS NULL OR e.Number = @Number)
AND (@Type IS NULL OR e.Type = @Type)
AND (@Code IS NULL OR a.Code = @Code)
To learn how to use parameters with ADO.NET, click here.
Setting parameters would look something like this:
command.Parameters["@Number"].Value = (string.IsNullOrEmpty(number) ? (object) DBNull.Value : number);
I think this is what you are after :
Just added a simple trick;
if(string.IsNullOrEmpty(sNumber))
sNumber="$$$"; //If sNumber is empty, then selection using sNumber= '$$$' will return nothing.
if(string.IsNullOrEmpty(sType))
sType="$$$" //If sType is empty, then selection using sType = '$$$' will return nothing.
"SELECT Number, Type, Code FROM EqNum, AreaCd " +
"WHERE EqNum.AreaId = AreaCd.AreaId
AND
(Code = " + int nCode + "
OR Number = '" + string sNumber + "'
OR Type = '" + string sType + "')"
OR using LIKE
:
if(string.IsNullOrEmpty(sNumber))
sNumber="$$$"; //If sNumber is empty, then selection using sNumber LIKE '%$$$%' will return nothing.
if(string.IsNullOrEmpty(sType))
sType="$$$" //If sType is empty, then selection using sType LIKE '%$$$%' will return nothing.
"SELECT Number, Type, Code FROM EqNum, AreaCd " +
"WHERE EqNum.AreaId = AreaCd.AreaId
AND
(Code = " + int nCode + "
OR Number LIKE '%" + string sNumber + "%'
OR Type LIKE '%" + string sType + "%')"
See an example at SQL Fiddle