2012-06-19 2 views
0

ASP.Net에 웹 서비스를 구축하여 방 목록을 보냅니다.SQL 쿼리에 대한 매개 변수를 선택적으로 설정하는 방법은 무엇입니까?

매개 변수는 쉼표로 구분 된 ID입니다.

문자열에 저장하고 SQL select 쿼리를 작성했습니다.

모든 매개 변수를 보내면 모든 것이 잘 작동하고 결과가 나타납니다. 하지만 4 개 미만을 보내면 오류가 발생합니다.

System.Data.SqlClient.SqlException: Incorrect syntax near ')'. 

입력 한 값만 선택하도록 SQL 쿼리에서 선택적 매개 변수를 설정하려면 어떻게해야합니까? 당신의 도움에 미리

internal static List<RAUM> Raum(string RAUMKLASSE_ID, string STADT_ID, string GEBAEUDE_ID, string REGION_ID) 
{ 
    List<RAUM> strasseObject = new List<RAUM>(); 
    string raumklasseid = RAUMKLASSE_ID; 
    string gebaudeid = GEBAEUDE_ID; 
    string stadtid = STADT_ID; 
    string regionid = REGION_ID; 

    using (SqlConnection con = new SqlConnection(@"Data Source=Localhost\SQLEXPRESS;Initial Catalog=BOOK-IT-V2;Integrated Security=true;")) 
    using (SqlCommand cmd = new SqlCommand(@"SELECT r.BEZEICHNUNG AS BEZEICHNUNG, r.ID AS ID FROM RAUM r WHERE RAUMKLASSE_ID IN (" + raumklasseid + ") AND STADT_ID IN (" + stadtid + ") AND GEBAEUDE_ID IN (" + gebaudeid + ") AND REGION_ID IN (" + regionid + ")", con)) 
    { 
     con.Open(); 

     using (SqlDataReader rdr = cmd.ExecuteReader()) 
     { 
      while (rdr.Read()) 
      { 
       if (rdr["BEZEICHNUNG"] != DBNull.Value && rdr["ID"] != DBNull.Value) 
       { 
        strasseObject.Add(new RAUM() 
        { 
         RaumName = rdr["BEZEICHNUNG"].ToString(), 
         RaumID = rdr["ID"].ToString() 
        }); 
       } 
      } 
     } 
    } 

    return strasseObject; 
} 

감사 :

여기에 지금까지 내 코드입니다.

+2

는이있을 수 있습니다 예를 들어, 쿼리를 덤프 : "... RAUM r에서 RAUMKLASSE_ID IN() ... "이 (가) 잘못되었습니다. 매개 변수에 값이있는 경우에만 각 제한을 추가해야합니다. –

+0

무슨 뜻인지 모르겠다. 더 자세히 설명해 주시겠습니까? –

+0

일부 코드와 함께 답변을 추가했습니다. –

답변

1

매개 변수 REGION_ID은 빈 문자열 상상해 확인 didnt한다.

...AND REGION_ID IN()... 

때문에이 AND REGION_ID IN (" + regionid + ")"regionid 변수가 빈 문자열로 대체됩니다 : 조회의 그 부분은 무엇인가있을 것입니다. 이것은 유효한 SQL 구문이 아니므로 해당 예외가 발생합니다.

이 같은 함수를 선언 :

private static void AppendConstrain(StringBuilder query, string name, string value) 
{ 
    if (String.IsNullOrWhiteSpace(value)) 
     return; 

    if (query.Length > 0) 
     query.Append(" AND "); 

    query.AppendFormat("{0} IN ({1})", name, value); 
} 

그런 다음 이런 식으로 쿼리를 작성하는 코드를 변경 :

StringBuilder constrains = new StringBuilder(); 
AppendConstrain(contrains, "RAUMKLASSE_ID", RAUMKLASSE_ID); 
AppendConstrain(contrains, "GEBAEUDE_ID", GEBAEUDE_ID); 
AppendConstrain(contrains, "STADT_ID", STADT_ID); 
AppendConstrain(contrains, "REGION_ID", REGION_ID); 

StringBuilder query = 
    new StringBuilder("SELECT r.BEZEICHNUNG AS BEZEICHNUNG, r.ID AS ID FROM RAUM r"); 

if (constrains.Length > 0) 
{ 
    query.Append(" WHERE "); 
    query.Append(constrains); 
} 

using (SqlCommand cmd = new SqlCommand(query.ToString(), con)) 
{ 
    // Your code... 
} 
+0

감사합니다. 귀하의 코드를 시도했지만 여전히 동일한 오류가 발생합니다. 이유를 모르겠다 –

+0

@ErayGeveci는 query.ToString()을 게시하고 여기에 게시합니다. –

+0

서버에있는 webservice를 기록하는 방법을 모르겠습니다. 솔루션에 대한 잘못된 검색 및 결과 쓰기 게시 –

0

저장 프로 시저를 작성하고 매개 변수를 전달하는 것이 더 좋은 방법 일 수 있습니다. 하지만 당신의 접근 방식에서는 값이 확실하지 않기 때문에 쿼리를 분리해야합니다. 그래서, 당신의 코드는 그런 일이 될 ..

테스트 스스로가, 내가 그것을

string raumklasseid = RAUMKLASSE_ID; 
     string gebaudeid = GEBAEUDE_ID; 
     string stadtid = STADT_ID; 
     string regionid = REGION_ID; 
     string whereClause = string.Empty; 

if (!string.IsNullorEmpty(raumklasseid)) 
{ 
    whereClause = "RAUMKLASSE_ID IN (" + raumklasseid + ")"; 
} 
if (!string.IsNullorEmpty(stadtid)) 
{ 
    if(string.IsNullorEmpty(whereClause) 
     whereClause = "STADT_ID IN (" + stadtid + ")"; 
    else 
     whereClause += "AND RSTADT_ID IN (" + stadtid + ")"; 
} 
if (!string.IsNullorEmpty(stadtid)) 
{ 
    if(string.IsNullorEmpty(whereClause) 
     whereClause = "STADT_ID IN (" + stadtid + ")"; 
    else 
     whereClause += "AND RSTADT_ID IN (" + stadtid + ")"; 
} 
if (!string.IsNullorEmpty(regionid)) 
{ 
    if(string.IsNullorEmpty(whereClause) 
     whereClause = "REGION_ID IN (" + regionid + ")"; 
    else 
     whereClause += "AND REGION_ID IN (" + regionid + ")"; 
} 

if(!string.IsNullorEmpty(whereClause) 
whereClause = "WHERE " + whereClause ; 

// now your cmd should be like that 

using (SqlCommand cmd = new SqlCommand(@"SELECT r.BEZEICHNUNG AS BEZEICHNUNG, r.ID AS ID FROM RAUM r " + whereClause , con)) 
관련 문제