在insert语句中使用别名

时间:2012-03-13 22:18:07

标签: .net sql postgresql

我是一个大多数时候都在使用ORM的SQL新手。我在以下查询中遇到别名问题:

command.CommandText = @"
    INSERT INTO permissions (userid, remoteid)
        SELECT userid as uid, :remoteid as rid
        FROM users
        WHERE companyid = :companyid
            AND NOT EXISTS (
                SELECT 1
                FROM permissions
                WHERE userid = uid
                AND remoteid = rid
            )";

command.Parameters.AddWithValue("companyid", companyId);
command.Parameters.AddWithValue("remoteid", resourceId);

执行查询时,出现以下错误:

ERROR: 42703: column "uid" does not exist

我做错了什么?别名是否应该像这样使用,是否可以在INSERT语句中使用?

1 个答案:

答案 0 :(得分:1)

怎么样:

command.CommandText = @"
    INSERT INTO permissions (userid, remoteid)
        SELECT userid, :remoteid as rid
        FROM users uid
        WHERE companyid = :companyid
            AND NOT EXISTS (
                SELECT 1
                FROM permissions
                WHERE userid = uid.userid
                AND remoteid = rid
            )";

command.Parameters.AddWithValue("companyid", companyId);
command.Parameters.AddWithValue("remoteid", resourceId);