Jamie
Jamie

Reputation: 3071

How to fix "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS" error?

I'm trying to run the following query on MS SQL 2012 Express:

Select (
    Select Id, Salt, Password, BannedEndDate
    from Users
    where username = '" + LoginModel.Username + "'
), (
    Select Count(*)
    From LoginFails
    where username = '" + LoginModel.Username + "'
    And IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "')"
);

But I get the following error:

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

How can I solve this problem?

Upvotes: 14

Views: 105503

Answers (2)

mortb
mortb

Reputation: 9869

Try this:

 Select 
    Id, 
    Salt, 
    Password, 
    BannedEndDate, 
    (Select Count(*) 
        From LoginFails 
        Where username = '" + LoginModel.Username + "' And IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "')
 From Users 
 Where username = '" + LoginModel.Username + "'

And I recommend you strongly to use parameters in your query to avoid security risks with sql injection attacks!

Hope that helps!

Upvotes: 7

Devart
Devart

Reputation: 122032

Try this one -

"SELECT 
       ID, Salt, password, BannedEndDate
     , (
          SELECT COUNT(1)
          FROM dbo.LoginFails l
          WHERE l.UserName = u.UserName
               AND IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "'
      ) AS cnt
FROM dbo.Users u
WHERE u.UserName = '" + LoginModel.Username + "'"

Upvotes: 7

Related Questions