2009-05-17 36 views
1

我有一個名爲itemIDs的逗號分隔的字符串(12,43,34,..),並且爲了將它用作參數,我需要將它轉換爲int,因爲db中的itemID是以int格式。在sql查詢中使用charindex

這是我寫的,但我得到一個錯誤說Incorrect syntax near the keyword 'as'.

using (SqlCommand searchResult = new SqlCommand("SELECT ItemID, Name, RelDate, Price, Status FROM item_k WHERE (itemID = cast(charindex(',',(@itemIDs as int))))", searchCon)) 

我無法弄清楚,什麼似乎是這裏的問題?

回答

2

你從哪裏獲取itemID?如果這是你產生mathematicaly一個字符串,而不是從外部來源可以使用:

... "SELECT ItemID, Name, RelDate, Price, Status FROM item_k WHERE itemID IN (" + itemIDs + ")" 
1

我想在這裏提出一個不同的方式爲您的WHERE子句。您可以使用IN來指定您的列表。

using (SqlCommand searchResult = new SqlCommand(" 
SELECT ItemID, Name, RelDate, Price, Status 
FROM item_k 
WHERE itemID IN (" + itemIDs + ")" 

對應於這樣的SQL:

SELECT ItemID, Name, RelDate, Price, Status 
FROM item_k 
WHERE itemID IN (12,43,34)