2009-05-17 22 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)