IF condition in where clause in SQL Server - sql-server

I need to write the if condition in the where clause of SQL where I wanted to define that if one column is null then search in another column in a row. I have used union but it's making the query slow to execute, so help me write this statement in the proper way.
This is the code I have right now:
SELECT *
FROM ACCOUNT
WHERE (IF ACCOUNTID IS NULL THEN REF_ACC_ID = 12 ELSE ACCOUNTID = 12)

you can use isnull built in function in sql server
like below link
w3schools
you can write this code for solve your problem
SELECT *
FROM ACCOUNT
WHERE isnull(ACCOUNTID ,REF_ACC_ID ) = 12

Related

Microsoft SQL Server: Error with Group By

I'm new to Microsoft SQL Server 2014. I run this SQL code:
SELECT TOP(10) 'DBSG' as seek_entity, *
FROM DBSG..PM00200
and get this result:
Next, I want to find out total line items for that entity with code below.
WITH vw_pm00200_all AS
(
SELECT TOP(10)
'DBSG' as seek_entity, *
FROM
DBSG..PM00200
)
SELECT
seek_entity,
COUNT(*) AS total
FROM
vw_pm00200_all
GROUP BY
1
Sadly, I get this error. I have no idea why it failed.
Msg 164, Level 15, State 1, Line 9
Each GROUP BY expression must contain at least one column that is not an outer reference.
Lastly, please advise is Microsoft SQL Server based on Transact-SQL?
It looks like you are running into this problem here: Each GROUP BY expression must contain at least one column that is not an outer reference
As the answer points out, grouping by a constant literal is pointless as it is the same for all results. Count(*) will return the same result as Count(*) with a GROUP BY.
If this is just test code and you plan on using a CASE statement (with different values) in place of the string literal, you may have better luck.
Yes, T-SQL is Microsoft SQL Server's flavor of SQL.

SQL Server 2008 - Force SQL Server to Return a Row when the where Clause Returns No Rows

I have a really simple SQL Server query that doesn't return a value. I'd like to see my query return a single row set with a space in it, but I can't seem to get it after a lot of time trying and searching! So, I've got to be doing something wrong and I really feel kind of dumb for having to post such a simple thing, but I can't seem to get it...
Here's the Select:
Select Session from Logins where Session = '123'
In my table the value '123' does not exist under the Session column...
So, I need this simple query to return a space as the value and not return an empty row set.
I've tried ISNULL, COALESCE and the little known IFNULL, all to no effect.
Interestingly, if I remove the where clause from the query it returns multiple rows correctly, none of them as nulls - as SQL Server should do, but when I put in my where clause in I get an empty row set. What I can't understand is why!
All you SQL Server gurus out there, could you please help me to develop a query that returns one column with one row that has a space in it when there is no return set for a where clause?
Thanks in advance,
Usually, you would want to perform this sort of logic in the client side rather than directly in the query.
But here is one way you can do it in pure SQL by putting your query in a CTE. Not sure if the CTE will get run twice though.
with cte as (
select session
from Logins
where session = '123'
)
select session
from cte
union all
select ' ' as session
where not exists (select null from cte)

Creating a new row in SSRS dataset SQL query to use in a report parameter

I am going round in circles with a bit of SQL and would appreciate some help.
I've looked up creating temp tables, nested Select statements (where advice seems to be to avoid these like the plague) and various uses of Case statements but I can't seem to find a solution that works. I'd say I'm beginner level for SQL.
I have a table with 10 relevant records. The query that works to return all the relevant entries in the table is:
SELECT
TblServAct.ServActId
,TblServAct.ServActName
FROM TblServAct
WHERE TblServAct.ServActExclude IS NULL
ORDER BY TblServAct.ServActName
Here is where I run into problems:
When the parameter (#YESNOActivity) = Yes, I want all the rows in the table to be returned. I have managed to do this with a CASE statement
...however when the parameter (#YESNOActivity) = No, I want ONLY ONE row to be returned which doesn't actually exist in the table (and should not be inserted into the actual table). The values that I need to insert are: ServActId = 101 and ServActName = 'Select YES in Parameter2 to filter by Service Activity'
For background, the reason I am doing this is because I have found SSRS report parameters to be especially difficult to conditionally format. I want to use the dataset above to return a message in a parameter (lets call it parameter2) that the user needs to select yes in (#YESNOActivity) in order to see the full selection list in parameter2.
If I can get this to work I can see lots of potential for re-use so all advice appreciated
Thanks
Eileen
I believe this should do the job, just include your parameter in the WHERE clause and UNION it with your own row of data.
SELECT
TblServAct.ServActId
,TblServAct.ServActName
FROM TblServAct
WHERE TblServAct.ServActExclude IS NULL
AND #YESNOActivity = 'Yes'
UNION ALL
SELECT
ServActId = 101
,ServActName = 'Select YES in Parameter2 to filter by Service Activity'
WHERE #YESNOActivity = 'No'
ORDER BY TblServAct.ServActName
One way is to use this query:
SELECT
TblServAct.ServActId
,TblServAct.ServActName
FROM TblServAct
WHERE TblServAct.ServActExclude IS NULL
AND 'Yes' = #YESNOActivity
UNION ALL
SELECT
101 AS ServActId
,'Select YES in Parameter2 to filter by Service Activity' AS ServActName
WHERE 'No' = #YESNOActivity
ORDER BY TblServAct.ServActName
Another way would be to create two data flows and use your variable in a constraint to send the processing to one or the other.
A third way would be to put an expression on the SQL command and use your variable to switch between two SQL statements.

adding WHERE clause to SQL Server Query panel

I'm in the Server Explorer and on the table name, I right-click on "Select Top 1000 Rows". The query panel show the SQL generated as
SELECT TOP 1000 [...] ,[....] , [....]
FROM [filename].[dbo].[TableName]
Now I want to add a simple WHERE clause.
I tried adding it like this:
WHERE [ColumnName] == 11
It's not working. I know this is a very basic question but I don't have much experience with working on SQL Server directly.
How do I fix the WHERE clause?
You don't need the double == sign SQL terminology is to use only a single =
From your example:
SELECT TOP 1000 [...] ,[....] , [....]
FROM [filename].[dbo].[TableName]
WHERE [ColumnName] = 11
C# uses double equal ("==") for conditional checks, in sql it is single "=" for predicates.

Use result of selection statement into another selection in stored procedure

How can I use the result of a select statement into another statement in a stored procedure in SQL Server? I am try to write this code
CREATE procedure [dbo].[ShowRequest] (#Id int)
AS
SELECT
Request.RequestId,
Request.UserId
INTO
reqTable
FROM
[User],[Request]
WHERE
Request.UserId = [User].UserId
AND
Request.RequestId = Id
/*another selection*/
SELECT
RequestProduct.ProductName
FROM
RequestProduct
/*ERROR:The multi-part identifier "ReqTable.id" could not be bound*/
WHERE
RequestProduct.RequestId = ReqTable.[id]
Try this:
CREATE procedure [dbo].[ShowRequest] (#Id int)
AS
SELECT
Request.RequestId,
Request.UserId
INTO
reqTable
FROM
[User],[Request]
WHERE
Request.UserId = [User].UserId
AND
Request.RequestId = Id
/*another selection*/
SELECT
ProductName
FROM
RequestProduct
WHERE
RequestId in
(
select id
from reqtable
)
It sounds like you actually just need to do a single selection:
SELECT
u.RequestId,
r.UserId,
rp.ProductName
FROM
[User] u
inner join
[Request] r
on
r.UserId = u.UserId
inner join
RequestProduct rp
on
rp.RequestId = r.RequestId
WHERE
r.RequestId = #Id
Generally, with SQL, you should decide what overall result you're trying to achieve, and then try to express it as a single statement - SQL Server's job (or any SQL product's) is to work out how best to construct the results. You shouldn't have to break down the problem into separate parts.
I don't know the etiquette here - this is a comment not a proposed answer but I want to make it easier for people to comment on my comment... downvote as appropriate... I don't want to just start a new question since I want the OP to see this.
You've got some alternatives but no one talked about why the first query didn't work or answered how to use the results of one query into another.
Why it didn't work: If the table "reqTable" existed and had a column named "id" at the time that your query was evaluated, SQL Server could have bound the name. You can use "eval" to put in sql that will be valid when it runs. For this problem that would be unjustifiably complex, but things like this must come up, I don't know if it's a regular tool in the toolbox of people who write a lot of stored procedures.
SQL Server 2005 and 2008 both have a feature called "CTE" you should read about that addresses the general question of "How do I use the results of one query in another query". They don't do anything subqueries absolutely can't do, but most of the time they are easier to write.
I have solved it. declare a table contains the result of first selection and use it in the second selection.
CREATE procedure [dbo].[ShowRequest] (#Id int)
AS
DECLARE #reqTable TABLE
(
ReqID int,
UserID int
)
INSERT INTO
#reqTable
SELECT
Request.RequestId AS 'ReqID',
Request.UserId
FROM
[User],[Request]
WHERE
Request.UserId = [User].UserId
AND
Request.RequestId = Id
/*another selection*/
SELECT
RequestProduct.ProductName
FROM
RequestProduct,#reqTable
WHERE
RequestProduct.RequestId = ReqID
Thanks for everyone who care about my question and spend his time to solve my problem

Resources