Conditional Query Results
Dec 19, 2006
Hello everybody,
After several attempts of writing the query, I had to post my
requirement in the forum.
Here is what I have, what I need and what I did.
Table A
Col1 Col2
1 Nm1
2 Nm2
3 Nm3
Table B
Col1 Col2
10 100
20 200
Table C
Col1 (A.Col1) Col2 (B.Col1)
1 10
2 10
Table D
Col1 (A.Col1) Col2
1 Value1
2 Value2
I need results based on below criteria,
1.
Criteria - B.Col2 = 100
Resultset
A.Col1 D.Col1
1 Value1
2 Value2
2.
Criteria - B.Col2 =""
A.Col1 D.Col1
1 Value1
2 Value2
3 NULL
3.
Criteria - B.Col2 =200
Empty resultset
Here is the query I tried, but looks its not working. Probably there is
a better way to do this.
DDL and DML statements:
create table #tab1 (a1 int, a2 nvarchar(20))
create table #tab2 (b1 int, b2 int)
create table #tab3 (c1 int, c2 int)
create table #tab4 (d1 int, d2 nvarchar(20))
insert into #tab1 values (1, 'nm1')
insert into #tab1 values (2, 'nm2')
insert into #tab1 values (3, 'nm3')
insert into #tab2 values (10, 100)
insert into #tab2 values (20, 200)
insert into #tab3 values (1, 10)
insert into #tab3 values (2, 10)
insert into #tab4 values (1, 'value1')
insert into #tab4 values (2, 'value2')
select
a.a1
, d.d2
from #tab1 a
left join #tab3 b
on a.a1 = b.c1
left join #tab2 c
on b.c2 = c.b1
left join #tab4 d
on a.a1 = d.d1
where
c.b2 = [100 or 200 or ''] or exists (select 1 from #tab4 d
where a.a1 = d.d1
and c.b2 = [100 or 200 or ''] )
The above query works well to give results for Criteria 1 and Criteria
3, but doesn't return for '' (criteria 2). I couldn't manage cracking
the solution. I shall try once again, but meanwhile if anyone could
help me in this, that would be great.
Thanks.
View 3 Replies
ADVERTISEMENT
Nov 6, 2007
This is my query:
SELECT Class.ClassID, Class.Comments, Class.Address1, City.City, Class.State, Instructor.FirstName, Instructor.LastName, ClassInstructor.IsPrimary
FROM Class
LEFT OUTER JOIN City ON City.CityID = Class.CityID
LEFT OUTER JOIN ClassInstructor ON ClassInstructor.ClassID = Class.ClassID
LEFT OUTER JOIN Instructor ON Instructor.InstructorID = ClassInstructor.InstructorID
WHERE Class.ClassID = @ClassID
AND ClassInstructor.IsPrimary=1
The problem is that if the class doesn't have an instructor yet, the query doesn't return results because even though I am using a LEFT JOIN on the class table, the "ClassInstructor.IsPrimary=1" statement will cause no results. I want results from the other class fields even if the class doesn't have an instructor.
I tried this and it works but seems kinda inefficient:
SELECT @cnt=COUNT(*)FROM ClassInstructor
WHERE ClassID = @ClassID
AND ClassInstructor.IsPrimary=1
IF @cnt>0
BEGIN
SELECT Class.ClassID, Class.Comments, Class.Address1, City.City, Class.State, Instructor.FirstName, Instructor.LastName, ClassInstructor.IsPrimary
FROM Class
LEFT OUTER JOIN City ON City.CityID = Class.CityID
LEFT OUTER JOIN ClassInstructor ON ClassInstructor.ClassID = Class.ClassID
LEFT OUTER JOIN Instructor ON Instructor.InstructorID = ClassInstructor.InstructorID
WHERE Class.ClassID = @ClassID
AND ClassInstructor.IsPrimary=1
END
Is there a better way to do this?
View 3 Replies
View Related
Jul 14, 2015
My source table has two columns... Policynum and PolicyStartdate and data looks like..
.
Policynum             PolicyStartdate
123GÂ Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 01/01/2012Â Â Â Â
456DÂ Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 02/16/2012Â Â Â Â Â
789AÂ Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 01/21/2012
163JÂ Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 05/25/2012
Now my output should return based on 3 parameters..
First two parameters are date range... let say @fromdt and @todt
Third parameter is @policynum
Scenario-1: Enter dates in date range param and leave policynum param blank
Ex: policystartdate between '01/01/2012 and '01/31/2012'.... It returns 1st and 3rd rows from above in the output
Scenario-2: enter policy num in policynum param and don't select any dates
Ex:Â policynum ='456D'Â Â Â Â It returns 2nd row in the output
Scenario-3: Select dates in date range param and enter policynum in param
Ex: policystartdate between '01/01/2012 and '01/31/2012' and policynum
='163J'. it should return only 4th row even though dates were selected(Override date range when policynum is entered in param and just return specified policynum row in the output)
I need t-sql code to get above results.
View 12 Replies
View Related
Apr 1, 2007
hi, like, if i need to do delete some items with the id = 10000 then also need to update on the remaining items on the with the same idthen i will need to go through all the records to fetch the items with the same id right? so, is there something that i can use to hold those records so that i can do the delete and update just on those records and don't need to query twice? or is there a way to do that in one go ?thanks in advance!
View 1 Replies
View Related
Feb 12, 2008
Hello. I currently have a website that has a table on one webpage. When a record is clicked, the primary key of that record is transfered in the query string to another page and fed into an sql statement. In this case its selecting a project on the first page, and displaying all the scripts for that project on another page. I also have an additional dropdownlist on the second page that i use to filter the scripts by an attribute called 'testdomain'. At present this works to an extent. When i click a project, i am navigated to the scripts page which is empty except for the dropdownlist. i then select a 'testdomain' from the dropdownlist and the page populates with scripts (formview) for the particular test domain. what i would like is for all the scripts to be displayed using the formview in the first instance when the user arrives at the second page. from there, they can then filter the scripts using the dropdownlist.
My current SQL statement is as follows.
SelectCommand="SELECT * FROM [TestScript] WHERE (([ProjectID] = @ProjectID) AND ([TestDomain] = @TestDomain))"
So what is happening is when testdomain = a null value, it does not select any scripts. Is there a way i can achieve the behaivour of the page as i outlined above? Any help would be appreciated.
Thanks,
James.
View 1 Replies
View Related
Mar 7, 2007
Hi again. Another problem though...
Can I make a query in if else statement? For example
int querynum;
if(querynum==1)<execute query1>
else if(querynum==2)<execute query2>
else <execute query3>
There is no problem with passing parameters(getquerynum) from my front end application to sql function. I can manage to do it. hehe.
the query looks like this:
DECLARE @querynum number
SET @querynum = @getquerynum
what i want to do is,
if(querynum==1) Select * from hremployees
else if(querynum==2) Select * from hrapplicants
else Select * from pspersonaldata
is it possible by having multiple queries in conditional statement?
if so, how to do it in sql language?
Thanks
-Ron-
View 14 Replies
View Related
Mar 15, 2007
I have a table having CusId, CusName, LocId and TvId among other fields.
I have 3 dropdown list which are are populated with cusid, locid and tovid.
I have added "Please Select" in all the 3 ddl with value -1.
Now i have written a sql statement as :
declare @CusId int
declare @LocId int
declare @TvId int
select CusId, CusName, LocId and TvId
From CustDetails
where CusId = @CusId
and LocId = @LocId
and TvId = @TvId
All i want is if any of the three variables has a value -1 then query should be modified. say @CusId has a value of -1 selected in dropdown list then query should become
select CusId, CusName, LocId and TvId
From CustDetails
where CusId IS NOT NULL
and LocId = @LocId
and TvId = @TvId
Please help me on this as i am totally new to sql.
Regards
Tingu
View 5 Replies
View Related
Apr 27, 2006
Hi,I'm trying to construct a query (in a stored procedure) which will have a number ofselection criteria based on input parameters. There are a number of these parameterswhose selection conditions they represent which all have to be true for a row to bereturned in the resultset.The basic query is:SELECT Store, StoreNumberFROM StoresWHERE ...I'm trying to come up with the WHERE clause.For example, I want to define a parameter named @ExcludeSpecialties which if it hasthe value 1, means to return all stores but exclude stores whose StoreNumber is inthe list (800, 802, 804). If the parameter has the value 0, then it means "don'tcare" and all StoreNumbers should be returned.One could certainly argue that there probably should have been an column in theStores row to indicate the store is a specialty store, rather than using a hard-wiredlist of numbers. But the current data schema cannot be easily changed. Besides, thelist never changes.Indeed, there is a Franchise bit column in the row which is selected by anotherparameter called @ExcludeFranchise whose WHERE predicate could be written as:WHERE Franchise = CASE WHEN @ExcludeFranchise = 1 THEN 0 ELSE Franchise ENDand if all the parameters were like this, I wouldn't be posting. Sadly, for theSpecialties test I'm stuck with a NOT IN list.This is easy enough to do in an IF/ELSE block, but there are several such similarparameters whose values may be specified in any combination. This, I think, makesIF/ELSE impractical as the number of IF/ELSE statements to handle all possiblecombinations would grow very quickly.I'm hoping there is a simple solution to this NOT IN list, and it's just that I can'tsee it.Can anyone help?Thanks,-- Jeff
View 2 Replies
View Related
Sep 23, 2007
Hi,
I have the following table in MsAccess
EmployeesA
empId integer,
empName varchar(60),
empAge integer,
empStatus char(1) - can be N,D or S - New, Deleted or Shifted
and the following in Sql2005
EmployeesB
Id smallint,
Name varchar(60),
Age int,
Status char(1) - Bydefault 'N'
I have written a Foreach File package that populates the sql server tables (EmployeesB) from Access(EmployeesA). However i want to check for a condition now.
If empStatus = N in EmployeesA, then insert a new record in EmployeesB
If empStatus = D in EmployeesA, then search for that field in the EmployeesB by passing empname and age and if found, mark the Status field in EmployeesB as 'D'
If empStatus = S in EmployeesA, then search for that field in the EmployeesB by passing empname and age and if found, mark the Status as 'S' in EmployeesB and insert a new row.
How do I do it for each table each row in EmployeesA using a foreach file loop?
Thanks,
ron
View 8 Replies
View Related
May 28, 2008
ok can someone tell me why i get two different answers for the same query. (looking for last day of month for a given date)
SELECT DATEADD(ms, - 3, DATEADD(mm, DATEDIFF(m, 0, CAST('12/20/2006' AS datetime)) + 1, 0)) AS Expr1
FROM testsupplierSCNCR
I am getting the result of 01/01/2007
but in query analizer I get the result of
12/31/2006
Why the different dates
View 4 Replies
View Related
Jun 13, 2007
I'm trying to simplify a SQL Stored Procedure.The query accepts an int, @ItemTypeID intI have the Query:SELECT ... FROM ItemList WHERE ItemTypeID = @ItemTypeIDor, if @ItemTypeID is 0,SELECT ... FROM ItemList Is there a way to do this query without doing:IF @ItemTypeID = 0BEGIN ...SELECT QUERY...ENDELSEBEGIN ...SELECT QUERY...END?
View 5 Replies
View Related
Sep 12, 2007
Dear Friends,
I am working on search customer information page.
I have 5 search options,
Name,
Email,
Order Number,
Product Name,
Order Date
I am using check boxes, I need to allow admin to enter above information and click on search,
How will I make my query and sends to DB server to pull up records which satisfies where clause:
For example,
Select * from orders where Email = #Email#
This is simple, but I can not hardcode all queries, I don€™t know in advance what different search option ADMIN may choose.
Any suggestion for logic or query make up,
Thanks,
Fahim.
View 1 Replies
View Related
Aug 28, 2006
SQL Server 2000. Here's what I have so far. The section of the query I need help with is highlighted in blue.
CREATE PROCEDURE dbo.GetByVersion
(
@targetVersion varchar(30),
@product varchar(50)
)
AS
SET NOCOUNT ON;
SELECT * FROM MyTable
WHERE (product = @product)
AND
CASE
WHEN @targetVersion='' THEN (targetVersion='')
ELSE (targetVersion LIKE @targetVersion + '%')
END
GO
I get a syntax error in the Stored Procedure editor on an equal sign in this line:
WHEN @targetVersion='' THEN (targetVersion='')
What I want is this (in psuedocode):
if @targerVersion is blank
search for records where the targetVersion column = blank
else
search for records where the targetVersion column starts with @targetVersion
Can anyone offer any suggestions as to how I might modify my query to do what I want? Any help is very much welcome - Thanks in advance! :-)
View 5 Replies
View Related
Apr 23, 2005
Hi,
I'm converting some direct SQL queries into stored procedures. The
original queries have conditional parts appended depending on certain
parameters like this:
Sql = "First part"
If certain condition then
Sql &= "Second part"
Endif
How could I do this in a stored procedure? So far I have made them like this:
IF @condition > 0
Fist part Second part
ELSE
First part
You can see that I have to maintain 'First part' in two locations. What is a better way of dealing with this?
Thanks!
Noc
View 3 Replies
View Related
Dec 20, 2007
Hi,
I need to implement some thing like this.
I have a query like
SELECT table1.col1
,€™n/a€™ _response
FROM table1
INNER JOIN table2
This is the query that get the report data for my report. Now I need to replace the second column with an actual response like €˜accepted€™ and €˜rejected€™. And these values should be a result of evaluation of this form
Statusarray[] = ResponseStoredProcedure(table1.col1)
If(Statusarray.count < 1)
Set _response = €˜accepted€™
Else
Get Statusarray[1]
Compare this to Statusarray[0]
Set _response = some result based on comparision.
The _response returned in the query should return the actual response based on this evaluation where ResponseStoredProcedure is sent the current row value for table1.col1.
How can this be done in sql(using SQL Server 2005)
PLZZZ HELP!!!!!!!!!
Thanks,
Hari
View 2 Replies
View Related
Dec 20, 2004
Hi:
In a very busy SQL2000 enterprise edition server with 8GB memory and 6 cpus sp3, I could not install a update trigger, unless all the appl connections are dropped. For this 24 HR running svr, could do it.
then I try to run a query as follows:
if exists (select rfABC.* A
from rfABC inner join remoteSvr.XYZDB.dbo.vwIP L
on A.Address = L.address and
A.metro <> L.metro
begin
print ' ---- Yes metroID <> LAMetro, start job exec.... -----'
insert into tempCatchMetroIDGPRS
select rfABC.*, metro, getdate()
from rfABC inner join remoteSvr.XYZDB.dbo.vwIP L on rfABC.Address = L.address and rfABC.metro <> L.metro
update rfABC A
set A.metro = L.metro
from rfABC A inner join remoteSvr.XYZDB.dbo.vwIP L on A.Address = L.address and A.metro <> L.metro
end
else
begin
print ' ---- no metroID <> LAMetro, skip job exec.... -----'
end
------------------------------
this query hang there could not execute. When I took off the if ... else condition, it run with like 0 second. Wondered if a 'busy' (which updates the IP address continueously) could cause above issues...
thanks
David
View 4 Replies
View Related
Sep 22, 2015
-- The 3rd query uses an incorrect column name in a sub-query and succeeds but rows are incorrectly qualified. This is very DANGEROUS!!!
-- The issue exists is in 2008 R2, 2012 and 2014 and is "By Design"
set nocount on
go
if object_id('tempdb.dbo.#t1') IS NOT NULL drop table #t1
if object_id('tempdb.dbo
[code]....
This succeeds when the invalid column name is a valid column name in the outer query. So in this situation the sub-query would fail when run by itself but succeed with an incorrectly applied filter when run as a sub-query. The danger here is that if a SQL Server user runs DML in a production database with such a sub-query which then the results are likely not the expected results with potentially unintended actions applied against the data. how many SQL Server users have had incorrectly applied DML or incorrect query results and don't even know it....?
View 2 Replies
View Related
Jul 30, 2015
For each customer, I want to add all of their telephone numbers to a different column. That is, multiple columns (depending on the number of telephone numbers) for each customer/row. How can I achieve that?
I want my output to be
CUSTOMER ID, FIRST NAME, LAST NAME, TEL1, TEL2, TEL3, ... etc
Each 'Tel' will relate to a one or more records in the PHONES table that is linked back to the customer.
I want to do it using SELECT. Is it possible?
View 13 Replies
View Related
Mar 7, 2008
Hello everyone,
Is there a way in order to execute a subscribed report based on a certain criteria?
For example, let's say send a report to users when data exist on the report else if no data is returned by the query
executed by the report then it will not send the report to users.
My current situation here is that users tend to say that this should not happen, since no pertinent information is contained in the report, why would they receive email with blank data in it.
Any help or suggestions will be much appreciated.
Thanks,
Larry
View 6 Replies
View Related
Feb 12, 2008
When I run the following query from Query Analyzer in SQL Serer 2005, I get a message back that says.
Command(s) completed successfully.
What I really need it to do is to display the results of the query. Does anyone know how to do this?
declare @SniierId as uniqueidentifierset @SniierId = '85555560-AD5D-430C-9B97-FB0AC3C7DA1F'declare @SniierAlias as nvarchar(50)declare @AlwaysShowEditButton as bitdeclare @SniierName as nvarchar (128)/* Check access for Sniier */SELECT TOP 1 @SniierName = Sniiers.SniierName, @SniierAlias = Sniiers.SniierAlias, @AlwaysShowEditButton = Sniiers.AlwaysShowEditButtonFROM SniiersWHERE Sniiers.SniierId=@SniierId
View 3 Replies
View Related
Aug 2, 2012
linking two tables together to get an end result
find below the code i have used
The first part of the query provides me with the info i need
SELECT sub.*,
case when rm_sales_band = '2M to 4M' then 'Kirsty' else RM end as rm
into #rmtmp
[Code].....
View 1 Replies
View Related
Jul 10, 2015
I have a query that performs a comparison between 2 different databases and returns the results of the comparison. It returns 2 columns. The 1st column is the value of the object being compared, and the 2nd column is a number representing any discrepancies.What I would like to do is use the results from this 1st query in the where clause of another separate query so that this 2nd query will only run for any primary values from the 1st query where a secondary value in the 1st query is not equal to zero.I was thinking of using an "IN" function in the 2nd query to pull data from the 1st column in the 1st query where the 2nd column in the 1st query != 0, but I'm having trouble ironing out the correct syntax, and conceptualizing this optimally.
While I would prefer to only return values from the 1st query where the comparison value != 0 in order to have a concise list to work with, I am having difficulty in that the comparison value is a mathematical calculation of 2 different tables in 2 different databases, and so far I've been forced to include it in the select criteria because the where clause does not accept it.Also, I am not a DBA by trade. I am a system administrator writing SQL code for reporting data from an application I support.
View 6 Replies
View Related
Aug 22, 2005
Hi,New to .Net and SQL. I have two tables that I have joined together. RentalControl_Main has the rental informationd and an Adjuster ID that links to the ADjuster table and the adjusters name. I am trying to create a report that gives the "Single" adjuster name and the totals for all of their contracts. I have a details report that gives each contract info. for each specific adjusters rentals. However, I want to just list the adjuster once and give all of their totals. In my SQL statement I have all of it written out and just need to knowwhat to do in place of 'Alex Early' that will give me all of the distinct adjusters.Do I need to code this on the page with a do while loop?Appreciate any help.SELECT SUM(dbo.RentalControl_Main.Rate) / COUNT(dbo.RentalControl_Main.Rate) AS AmtAvg, SUM(dbo.RentalControl_Main.DaysBilled) / COUNT(dbo.RentalControl_Main.DaysBilled) AS DayAvg, SUM(dbo.RentalControl_Main.Rate * dbo.RentalControl_Main.DaysBilled) / COUNT(dbo.RentalControl_Main.Rate) AS TotAvgFROM dbo.RentalControl_Main INNER JOIN dbo.RentalControl_Adjuster ON dbo.RentalControl_Main.AdjusterID = dbo.RentalControl_Adjuster.AdjusterIDWHERE (dbo.RentalControl_Adjuster.AdjusterName = 'Alex Early' AND (dbo.RentalControl_Main.DateClose IS NOT NULL) AND (dbo.RentalControl_Main.AgencyID = '2')
View 1 Replies
View Related
Apr 20, 2004
I was wondering if there was a keyword that would allow you to return the number of results from a query such as (this is fake just giving an example so that someone can give me the real answer)
select TotalReturned
from table
where field=""
View 7 Replies
View Related
Oct 7, 1999
I am a beginner with SQL, so please excuse any ignorance here.
Under SQL 6.5, when executing a SELECT DISTINCT query against a table in a certain database, the results were returned alphabetized. Now, after migrating the database to SQL 7.0, the same query does not return the results alphabetized. If I add an index for the column specified in the query to the table, the results come back alphabetized. Is there any way to correct this other than adding indexes for all columns in all tables that are queried in this manner?
TIA,
Paige
View 2 Replies
View Related
Mar 2, 2005
I am running the same exact query in SQL 2000 and I get different results. Should I try running DBCC CHECKDB and look for errors?
View 5 Replies
View Related
Apr 30, 2008
Hi,
I have this line of code that when run in the query doesn't return anything:
srv.AGENT_S_ACC_CODE IN ('" & Replace(Replace(Parameters!arcode.Value," ",""),",","','") & "')
The parameter is setup and the query works when I hardcode it with a value but will not return anything with this, does anyone know why?
Thanks,
Rhonda
View 2 Replies
View Related
Oct 25, 2006
Hi guys, say i wrote a query that returns 1,000 records.. what kinda query could i write that only returns say the first 50 records of the 1,000 recs..
View 4 Replies
View Related
May 13, 2007
Hello,
I want to select all the customerIDs where an email address exists. Easy: select customerid from customers where emailaddress = @emailaddress
Now I want to use the resulted customerIDs from the above query as a parameter to select all the email addresses with emailstatus equal to 3.
How do I create this type of while statement in a stored procedure? I prefer to not create a temporary table.
My idea was to do it like this:
select emailaddress from emailaddresseswhere emailstatus = 3 and customerid = (select customerid from customers where emailaddress = @emailaddress)
This doesn't seems to work. I get the error:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
thanks
View 4 Replies
View Related
Jul 17, 2007
I have a pretty big SQL query with a one to many sort of relationship...
There are client accounts that we're reporting on. Each account has four different historical categories attached. Each historical category can have maybe fifty entries in each, sorted by date.
I need to figure out how to grab the unique accounts and show only the three most recent results per each historical subcategory with the account... the three most current results from each of the four subcategories, displayed by the parent client account number.
I've created four views to isolate the subcategories as a start, thinking I could bring them into a parent query ...
but my question would be... how do I generate JUST the top three historical transactions by account number? If I select TOP 3, I get only the 3 newest in the MASTER LIST, not per client account, which is what I need to do.
Does this make sense? I could really use a good SQL helping hand with this one.
Thank you!
View 12 Replies
View Related
Oct 17, 2007
Can anyone give me the basics of speeding up reports that use queries or views or nested views?
Current reports are now taking over 2 minutes to show.We have thousands and sometimes even millions of records to report against.Queries have 4 and 5 table joins etc.
We are using ASP.NET 2.0 in Visual Studio 2005 and Crystal Reports.
Thanks
View 4 Replies
View Related
Sep 1, 2004
Hi,
I would like to use the result table of the first query in a number of other queries. How do I do this ?
Thanks.
View 2 Replies
View Related
Jan 4, 2006
I have a database with some over normalized tables in it. The best I can do with one query is get the file ID. In the second query I want to get all the file names, based on all the fileID's I got from the first query. How would I go about doing this?
View 5 Replies
View Related