SQL SELECT返回以下列表:(如果id存在,则为cols)

时间:2014-05-20 14:04:40

标签: sql sql-server database

给出一个ID列表,比如user1,user2,user3;我需要构造一个查询,该查询将返回一个列表,该列表仅包含数据库中存在的列表,例如user1,user2。

我当前的实现如下(无效的SQL语句):

String queryString = ""
                + "IF EXISTS (SELECT cols... "
                + "FROM table "
                + "WHERE userID "
                + "IN (" + ids + ")";
        if ( ! includeDeleted ) {
            queryString += " AND u.DELETED = 'N'";
        }
        queryString += ") BEGIN "
                + "SELECT cols... " 
                + "FROM table "
                + "WHERE userID "
                + "IN (" + ids + ")"
                ;
        if ( ! includeDeleted ) {
            queryString += " AND u.DELETED = 'N'";
        }
        queryString += " END";

1 个答案:

答案 0 :(得分:0)

这应该是查询:

select * FROM MYTABLE where USERID IN ('user1', 'user4', 'user3');

这是DEMO

然后使用参数创建查询的代码:

String[] accountIds = {.... your IDs ...}

StringBuilder query = new StringBuilder();
query.append("FROM table t WHERE t.userID IN (");
    for (int i = 0; i < userIds.length; i++) {
        if (!query.toString().endsWith("(")) {
            query.append(", ");
        }
        query.append("?");
    }
    query.append(")");

    if ( ! includeDeleted ) {
        query.append(" AND t.DELETED = 'N'");
    }