Select statment from multiple tables, with variable input

前端 未结 3 1703
自闭症患者
自闭症患者 2021-01-16 09:17

I have two tables: AreaCode and EquipmentNumber.

+------------------------------------+
| AreaCd                             |
|---         


        
相关标签:
3条回答
  • 2021-01-16 09:24

    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 + "'
    
    0 讨论(0)
  • 2021-01-16 09:28
    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);
    
    0 讨论(0)
  • 2021-01-16 09:43

    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

    0 讨论(0)
提交回复
热议问题