2016-03-03 45 views
0

請看看下面的代碼Parameters.Add()不涉及查詢的情況下,工作在C#「是否存在」語句

string SearchQuery = @"if exists (select * from table where colName = @colNameVal) select 1 else select 0"; 
AseConnection connection = new AseConnection(); 
connection.ConnectionString = connectionString; 
connection.Open(); 
try 
{ 
    AseCommand selectCommand = new AseCommand(SearchQuery, connection); 
    selectCommand.Parameters.Add(new AseParameter("@colNameVal", AseDbType.NVarChar, 13)).Value = "123"; 
    int doesValExist = (int)selectCommand.ExecuteScalar(); 
} 
catch(Exception ex) 
{ 

} 

我使用Sybase.AdoNet4.AseClient。上面的代碼拋出AseException與以下消息

「必須聲明變量'@colNameVal'」。

但以下查詢正在工作select * from table where colName = @colNameVal

所以我假設在if exists語句的情況下添加參數會有一些問題。是否有任何解決方法來傳遞參數?

+0

嘗試設置:selectCommand.CommandType = CommandType.Text –

+0

你試過'Parameters.AddWithValue' – ninja

+0

都嘗試你的建議,而不是工作。獲取相同的錯誤。 –

回答

0
string SearchQuery = @"select count(*) from table where colName = @colNameVal"; 
AseConnection connection = new AseConnection(); 
connection.ConnectionString = connectionString; 
connection.Open(); 
try 
{ 
    AseCommand selectCommand = new AseCommand(SearchQuery, connection); 
    selectCommand.Parameters.Add(new AseParameter("@colNameVal", AseDbType.NVarChar, 13)).Value = "123"; 
    int doesValExist = (int)selectCommand.ExecuteScalar(); 
} 
catch(Exception ex) 
{ 

} 
+0

不工作。獲取相同的錯誤消息 –

+0

您可以使用文字格式,也許這可能工作。多年以來,我一直沒有用過Sybase,之前的代碼是在SQL Server中工作的。 –

+0

這將工作,但有一個sql注入的可能性,這就是爲什麼我想要避免這種情況。 –

相關問題