Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 438
Jamie Avatar asked Jul 01 '13 11:07

Jamie


People also ask

What are expressions in the SELECT list SQL?

An expression in a select list can be composed of any of the previous items with the following restrictions: Functions must be supported by ActiveSpaces. A select list cannot contain an expression, if it also contains an aggregate function. An expression cannot contain an aggregate function.

Which one is correct syntax for subquery with SELECT statement?

Subqueries must be enclosed within parentheses. A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns. An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY.

How do you introduce an existing subquery?

A subquery that is introduced with exists is different from other subqueries, in these ways: The keyword exists is not preceded by a column name, constant, or other expression. The subquery exists evaluates to TRUE or FALSE rather than returning any data.

How do you write a subquery in a SELECT statement in SQL?

The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or inside another subquery. A subquery is usually added within the WHERE Clause of another SQL SELECT statement. You can use the comparison operators, such as >, <, or =.


1 Answers

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!

like image 87
mortb Avatar answered Nov 08 '22 20:11

mortb