Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return a default record from a sql query

I have a sql query that I run against a sql server database eg.

SELECT * FROM MyTable WHERE Id = 2

This may return a number of records or may return none. If it returns none, I would like to alter my sql query to return a default record, is this possible and if so, how? If records are returned, the default record should not be returned. I cannot update the data so will need to alter the sql query for this.

like image 582
amateur Avatar asked Mar 08 '12 11:03

amateur


People also ask

How do you return a default value in SQL query?

The DEFAULT() function returns the default value for table column. DEFAULT value of a column is a value used in the case, there is no value specified by user. In order, to use this function there should be a DEFAULT value assign to the column.

How do I return a SQL record?

SELECT statements An SQL SELECT statement retrieves records from a database table according to clauses (for example, FROM and WHERE ) that specify criteria. The syntax is: SELECT column1, column2 FROM table1, table2 WHERE column2='value';


3 Answers

Another way (you would get an empty initial rowset returned);

SELECT * FROM MyTable WHERE Id = 2
IF (@@ROWCOUNT = 0)
   SELECT ...
like image 115
Alex K. Avatar answered Sep 20 '22 23:09

Alex K.


SELECT TOP 1 * FROM (
SELECT ID,1 as Flag FROM MyTable WHERE Id = 2
UNION ALL
SELECT 1,2
) qry
ORDER BY qry.Flag ASC
like image 35
Mike Miller Avatar answered Sep 20 '22 23:09

Mike Miller


You can have a look to this post. It is similar to what you are asking Return a value if no rows are found SQL

I hope that it can guide you to the correct path.

like image 22
Aristotelis Kostopoulos Avatar answered Sep 23 '22 23:09

Aristotelis Kostopoulos