Trouble With Case Statement And IN Subquery

Mar 27, 2007

I have the following in my WHERE clause for my Sql Server Reporting Services 2000 report (the user can use the parameter @MaxRevs to view all numbers (colNumber) or only the max of colNumbers when grouped by colParentNumber):



AND (tblMain.colNumber IN CASE @MaxRevs WHEN '' THEN '(SELECT colNumber FROM tblMain)' ELSE '(Select max(colNumber) From tblMain Group By [colParentNumber])' END))



I get the following error:
1. ADO error: Syntax error or ADO access error

I've used Case in the past, but it was for a "Like" portion in my WHERE clause.



The following doesn't seem to help me either in the SQL portion:


IF @MaxRevs = '' SELECT ....
ELSE
SELECT ....

With the above query, nothing is ever returned. I can even name the parameter to @MaxRevs55, which doesn't even exist, and the report just brings back a blank page w/o any errors.



Thanks!

View 2 Replies


ADVERTISEMENT

Subquery In Case Statement

Jul 23, 2005

Hi all, first, let me preface this by saying that I am very new to sqlserver, coming from oracle.Here is my problem: I would like to have a case statement (similar todecode in oracle) that will test a query for a null value. Here is mystatement:SELECTCASE(SELECT MAX(SEQ) + 1FROM [TRANSACTION]) WHEN NULLTHEN 0ELSE(SELECT MAX(SEQ) + 1FROM [TRANSACTION]) ENDIt functions correctly if there is a value for MAX(SEQ) + 1, otherwiseit returns null. It's as if the test for null fails. I hope thatmakes sense.This will ultimately be in an insert statement; I have taken it to thebare minimum to better understand where the problem is.Please let me know if I am doing something dumb. Does this sort ofthing have to in a stored procedure?Anyway, thanks for any help. have a great day!Ryan

View 6 Replies View Related

Having Trouble With In Keyword ; Maybe Need A Subquery?

Aug 2, 2007

 I am displaying advertisers on a dynamic .net page that users will
view via querystrings from a county  page,  then a city page , as they
can pick a zone , then view the advertiser's ad  predicated on the
zone they pick. I want to have advertisers on a premium plan that can
be viewed in all areas of the city, regardless what zone the user
picks. Trying the below does not suffice my resultset (the queriedzone
is a variable as the request.querystring for the zone ; 'all' is the
indicator for an advertiser who should be seen in all zones)

sqlstr = "select company, address, email from advertisers where zone IN ('" + queriedzone + "','all') "
??? thanks in advance ed

View 1 Replies View Related

Trouble With Correlated Subquery, Example Using Northwind

Aug 13, 2005

Suppose I have this query, which shows each order and the price of the most expensive item in each order:

SELECT Ord.OrderID, Ord.OrderDate,     MAX(OrdDet.UnitPrice) AS maxUnitPrice
FROM Northwind.dbo.[Order Details] AS OrdDet     INNER JOIN     Northwind.dbo.Orders AS Ord    ON Ord.OrderID = OrdDet.OrderID
GROUP BY Ord.OrderID, Ord.OrderDate

I need to also show the ProductID that has MaxUnitPrice from the Order
Details.  I can't just add ProductID to the select list because
I'd have to group by it, and then I'd get a row for each product,
instead of a row for each order... I think I need a correlated subquery
but can't work out how to do it!

View 1 Replies View Related

CASE WHEN With Subquery

Aug 10, 2005

I'm trying to create an aliased field on the fly in my sql string to use later in my datagrid, but having a tuff time coordinating the right CASE WHEN together with a subquery:
amtA = (select b.salesamount from b WHERE b.BoardDate = '" + day1 + "')
CASE WHEN b.salesamount  > 0 THEN 'amtA' ELSE NULL END , the above will not give me an error, but it displays a blank datagrid when posting a date from a calendar to view a datagrid with information for that particular date.What I want to accomplish is making amtA an aliased field - the salesamount from the day before. the user will click on a calendar date from the page before and view data for that date, but 'amtA' will be the salesamount from the previous day (already configured in c#: DateTime day1;day1 = requestedday.AddDays( -1);)and i will want to display 'amtA' in a column in my datagrid (eventually will do a sum with day2, day3, etc for a weekly total).Just wondering the best way to parse yesterday's 'amtA' and use it as an aliased field namethanks in advancenetsports

View 4 Replies View Related

Subquery Inside Case?

Jun 8, 2008

Hello,

I am trying to do something like this:

select (CASE
WHEN tableA.col = 'a' then 'A'
ELSE (select table3.col1
from tableA, table 2, table3
where tableA.id = table2.id
and table2.id = table3.id )END ) as TEST
from tableA


But the problem is that the part in bold returns more than one row..
i want it to be select table3.col1
from tableA, table 2, table3
where tableA.id = table2.id
and table2.id = table3.id
for every value of tableA.col.

How do I do this?

View 2 Replies View Related

Case Statments & Subquery

Nov 2, 2007

Hope someone can help;

I have a table with a list of payment information i have three other tables that store different types of commission rates that were active at a particular time.

Payments table – holds all payments received by customers

DirectRate table – holds the Direct rate active between start and end dates
ComRate table – holds the Commission rate active between start and end dates
FieldRate table – holds the Field rate active between start and end dates


Basically I am trying to get the total value of commission on all payments for all the different rates. To give you an example one payment can be of type Direct which would have to have the correct payment rate applied from the DirectRate table for the correct date range, this also applies for payments that are of type ComRate & FieldRate.

So I have the following SQL

SELECT CASE
WHEN dp.ReceivedByID = 1
THEN

dp.Amount * ((Select tF.Rate From dbo.mTrackerFeeChange tF where tF.ClientID=d.ClientID and tF.ContractID=d.ContractID AND ((dp.PaymentOn >= tF.StartDate AND dp.PaymentOn <= tF.EndDate) or (dp.PaymentOn >= tF.StartDate AND tF.EndDate IS NULL)))/100)

WHEN dp.ReceivedByID = 2
THEN

dp.Amount * ((Select tD.Rate From dbo.mTrackerDirectChange tD where tD.ClientID=d.ClientID and tD.ContractID=d.ContractID AND ((dp.PaymentOn >= tD.StartDate AND dp.PaymentOn <= tD.EndDate) or (dp.PaymentOn >= tD.StartDate AND tD.EndDate IS NULL)))/100)

ELSE

dp.Amount * (((Select tF.Rate From dbo.mTrackerFeeChange tF where tF.ClientID=d.ClientID and tF.ContractID=d.ContractID AND ((dp.PaymentOn >= tF.StartDate AND dp.PaymentOn <= tF.EndDate) or (dp.PaymentOn >= tF.StartDate AND tF.EndDate IS NULL))) + (Select tFe.Rate From dbo.mTrackerFieldChange tFe where tFe.ClientID=d.ClientID and tFe.ContractID=d.ContractID AND((dp.PaymentOn >= tFe.StartDate AND dp.PaymentOn <= tFe.EndDate) or (dp.PaymentOn >= tFe.StartDate AND tFe.EndDate IS NULL))))/100)

END

From
dbo.DebtPayment dp,
dbo.ImportBatchItem bi,
dbo.Debt d
where
d.DebtID=dp.DebtID
AND dp.DebtID=bi.ItemID
AND bi.ImportBatchID=2


I am using dp.ReceivedByID to assertain the payment type then depending upon that using the case statement to multiply the amount by the correct rate for the correct date range in the correct table. This sql works fine but it gives me a list of commision values, one for each payment. My problem is when I try to do a sum on this case statement I get an error

“Cannot perform an aggregate function on an expression containing an aggregate or a subquery�

any help most appriciated

p

View 7 Replies View Related

Case, Joins And NULL Trouble

Jul 23, 2005

HiConsider two tablesid1 code1----------- -----1 a2 b3 cid2 code2 value----------- ----- -----------1 a 02 a 13 b 1They are joined on the code field.For each code, I want the maximum corresponding value. If the valuedoesn't exist (corresponding code in second table doesn't exist), I wanta NULL field returned.The result should look like this:code2 value----- -----------a 1b 1c NULLI can't get it to include the NULL row.While there are uniqe ID's in this example, the real life example uses ahorrible four field compound key.Any help would be appreciated.Ger.The above example can be recreated by the following script.DROP table #temp1DROP table #temp2SELECT 1 AS 'id1', 'a' AS 'code1'INTO #temp1UNIONSELECT 2, 'b'UNIONSELECT 3, 'c'SELECT 1 AS 'id2', 'a' AS 'code2', 0 AS valueINTO #temp2UNIONSELECT 2, 'a', 1UNIONSELECT 3, 'b', 1SELECT code2, valueFROM #temp1 t1LEFT JOIN #temp2 t2 ON t1.code1 = t2.code2WHERE CASEWHEN t2.value IS NULL THEN 1WHEN t2.value = 0 THEN 2WHEN t2.value = 1 THEN 3END = (SELECTMAX( CASEWHEN value IS NULL THEN 1WHEN value = 0 THEN 2WHEN value = 1 THEN 3END )FROM#temp2WHEREcode2 = t2.code2)

View 5 Replies View Related

Subquery, Select Case, Pivot Help. Is There An Easier Way?

Apr 12, 2008



I'm trying to select from a table with three columns. I want these columns to be spread out among multiple columns based on the values. I hope someone can shed some light on this. I might be able to use pivot, but don't know how the syntax would roll for this.

Here is the example of dummy values and the output I am trying to obtain.




drop table table1

create table table1

(Category int, Place int, Value int)

insert into table1 values

(1, 1, 20)

insert into table1 values

(1,2, 12)

insert into table1 values

(1,3, 30)

insert into table1 values

(2,1, 34)

insert into table1 values

(2,2, 15)

insert into table1 values

(2,3, 78)



select Category,

(select top 1 value from table1 where place = 1 and Category = t1.Category) as place1,

(select top 1 value from table1 where place = 2 and Category = t1.Category) as place2,

(select top 1 value from table1 where place = 3 and Category = t1.Category) as place3

from Table1 t1

group by Category




Thanks for the help.

View 5 Replies View Related

Problem Using Result From CASE In Another CASE Statement

Nov 5, 2007

I have a view where I'm using a series of conditions within a CASE statement to determine a numeric shipment status for a given row. In addition, I need to bring back the corresponding status text for that shipment status code.

Previously, I had been duplicating the CASE logic for both columns, like so:




Code Block...beginning of SQL view...
shipment_status =
CASE
[logic for condition 1]
THEN 1
WHEN [logic for condition 2]
THEN 2
WHEN [logic for condition 3]
THEN 3
WHEN [logic for condition 4]
THEN 4
ELSE 0
END,
shipment_status_text =
CASE
[logic for condition 1]
THEN 'Condition 1 text'
WHEN [logic for condition 2]
THEN 'Condition 2 text'
WHEN [logic for condition 3]
THEN 'Condition 3 text'
WHEN [logic for condition 4]
THEN 'Condition 4 text'
ELSE 'Error'
END,
...remainder of SQL view...






This works, but the logic for each of the case conditions is rather long. I'd like to move away from this for easier code management, plus I imagine that this isn't the best performance-wise.

This is what I'd like to do:



Code Block
...beginning of SQL view...
shipment_status =
CASE
[logic for condition 1]
THEN 1
WHEN [logic for condition 2]
THEN 2
WHEN [logic for condition 3]
THEN 3
WHEN [logic for condition 4]
THEN 4
ELSE 0
END,


shipment_status_text =

CASE shipment_status

WHEN 1 THEN 'Condition 1 text'

WHEN 2 THEN 'Condition 2 text'

WHEN 3 THEN 'Condition 3 text'

WHEN 4 THEN 'Condition 4 text'

ELSE 'Error'

END,
...remainder of SQL view...


This runs as a query, however all of the rows now should "Error" as the value for shipment_status_text.

Is what I'm trying to do even currently possible in T-SQL? If not, do you have any other suggestions for how I can accomplish the same result?

Thanks,

Jason

View 1 Replies View Related

SQL Server 2012 :: Update Statement With CASE Statement?

Aug 13, 2014

i was tasked to created an UPDATE statement for 6 tables , i would like to update 4 columns within the 6 tables , they all contains the same column names. the table gets its information from the source table, however the data that is transferd to the 6 tables are sometimes incorrect , i need to write a UPDATE statement that will automatically correct the data. the Update statement should also contact a where clause

the columns are [No] , [Salesperson Code], [Country Code] and [Country Name]

i was thinking of doing

Update [tablename]
SET [No] =
CASE
WHEN [No] ='AF01' THEN 'Country Code' = 'ZA7' AND 'Country Name' = 'South Africa'
ELSE 'Null'
END

What is the best way to script this

View 1 Replies View Related

How To Write Select Statement Inside CASE Statement ?

Jul 4, 2006

Hello friends,
I want to use select statement in a CASE inside procedure.
can I do it? of yes then how can i do it ?

following part of the procedure clears my requirement.

SELECT E.EmployeeID,
CASE E.EmployeeType
WHEN 1 THEN
select * from Tbl1
WHEN 2 THEN
select * from Tbl2
WHEN 3 THEN
select * from Tbl3
END
FROM EMPLOYEE E

can any one help me in this?
please give me a sample query.

Thanks and Regards,
Kiran Suthar

View 7 Replies View Related

Transact SQL :: Update Statement In Select Case Statement

May 5, 2015

I am attempting to run update statements within a SELECT CASE statement.

Select case x.field
WHEN 'XXX' THEN
  UPDATE TABLE1
   SET TABLE1.FIELD2 = 1
  ELSE
   UPDATE TABLE2
   SET TABLE2.FIELD1 = 2
END
FROM OuterTable x

I get incorrect syntax near the keyword 'update'.

View 7 Replies View Related

IF...ELSE Statement Trouble

Apr 17, 2000

Take a look at this code:

CREATE PROCEDURE sp_addCustomer

@fnamechar(25),
@lnamechar(25),
@companyNamechar(30),
@addressvarchar(50),
@zipvarchar(10),
@citychar(20),
@countrychar(20),
@emailchar(30)

AS

IF @email = (SELECT email FROM customers WHERE @email = email)
PRINT 'This customer is already in the database'
ELSE
PRINT 'New Customer Added'
INSERT INTO customers
VALUES (@fname,@lname, @companyName, @address, @zip, @city, @country, @email)

Looks pretty straightfoward, however when I add a duplicate customer, I get the 'This customer is already in the database' message and then the record is added. I don't know why this is happening. Can anyone help?

Thank you,
Nathan

View 2 Replies View Related

Trouble With 'TOP' Statement

Jun 12, 2006

Background:

I am using standard ASP to connect and select records from a SQL Server 2000 database. My goal is to select the 3 most recent records that match my criteria.

Problem: When I run my query and display the records without the 'TOP 3' statment all records matching my criteria are predictably returned. However, when I add the 'Top 3' statement only one record is returned.

Here is the SQL code I am using to select my records:


Code:

strSql = "SELECT TOP 3 GroupImageName, groupImageDate "
strSql= strSql & "FROM groupImages "
strSql= strSql & "WHERE groups_id='" & groups_id & "' "
strSql= strSql & "ORDER BY groupImageDate"

set rs=conn.execute(strSql)



and here is the code I use to display the records. There isn't any formatting yet as I am attempting to get the expected results before adding any formatting to the page:


Code:

if not rs.eof then
do while not rs.eof
response.Write(rs("GroupImageName"))
rs.movenext
loop
end if



Even if I remove the 'ORDER BY' statment I am still only seeing 1 record. If I remove the 'top 3' statement 9 records are returned!

Any help would be appreciated. Thanks.

View 1 Replies View Related

Trouble With IF Statement

Sep 19, 2006

Ok, I'm about to pull all my hair out.

This is quite an easy query but it's not working.

IF (SELECT @@VERSION) LIKE 'Microsoft SQL Server 2000%'
BEGIN
SELECT * FROM msdb..sysjobschedules
END

IF (SELECT @@VERSION) LIKE 'Microsoft SQL Server 2005%'
BEGIN
SELECT * FROM MSDB..SYSJOBS
END

This does not work either:

IF (SELECT @@VERSION) LIKE 'Microsoft SQL Server 2000%'
BEGIN
SELECT * FROM msdb..sysjobschedules
END
ELSE
BEGIN
SELECT * FROM MSDB..SYSJOBS
END

Nomatter what SQL Server version I use to run the script, it runs the complete script as if there is no IF statement

Does anyone see what I'm doing wrong here?

Thanks!

Worf

View 5 Replies View Related

SubQuery In An Insert Statement?

Dec 7, 2000

Hi Everyone,

I want to insert a row in a table with 2 fields.

The data for the first column comes from a variable
and the data for the second column comes from a select query

can i insert the record in one sql statement like

************************************************** *************

declare @var1 int
set @var1 = 5

insert into mytable1 (field1,field2)
values
(@var1,select field1 from mytable2 where field2 = 10)

************************************************** ***************

where field2 in mytable2 is a primary key.


Awaiting a reply!

Thanks,
saad.

View 1 Replies View Related

How To Add Subquery To Delete Statement

Apr 28, 2015

I have to write a delete statement that deletes all customers that have not put in an order I must use a subquery in the exist operator.

View 5 Replies View Related

Subquery In SELECT Statement Before FROM

Nov 19, 2006

Hello!

I can use querys like these in Access:

SELECT Field1,
(SELECT Field2 FROM Table2 WHERE Key=1) AS Field2 FROM Table1
SELECT Field1,
(SELECT Count(Field2) FROM Table2 ) AS Field2 FROM Table1

But when I
try execute it with SQL Server Everywhere it says "Token in error
=
SELECT".

Is there some kind of limitations to do this with SQL Everywhere? SQL Everywhere seems to be nice compared with Access and JET but for my project it's useless if I can't use subquerys.

-Teemu

View 3 Replies View Related

Subquery In Update Statement

May 19, 2008

I am executing the following statement in SQL 2005 and it fails with:


Cannot perform an aggregate function on an expression containing an aggregate or a subquery.




update #tmp_rpt

set [value] = (select sum([value]) from #tmp_rpt a where a.project_id = #tmp_rpt.project_id and a.sum_date < = #tmp_rpt.sum_date)

from #tmp_rpt



I am tryng to perform a running total.

This doesn't appear to be an aggregate in another aggregate or subquery.

Thanks,

Greg

View 2 Replies View Related

Case Statement Error In An Insert Statement

May 26, 2006

Hi All,
I've looked through the forum hoping I'm not the only one with this issue but alas, I have found nothing so I'm hoping someone out there will give me some assistance.
My problem is the case statement in my Insert Statement. My overall goal is to insert records from one table to another. But I need to be able to assign a specific value to the incoming data and thought the case statement would be the best way of doing it. I must be doing something wrong but I can't seem to see it.

Here is my code:
Insert into myTblA
(TblA_ID,
mycasefield =
case
when mycasefield = 1 then 99861
when mycasefield = 2 then 99862
when mycasefield = 3 then 99863
when mycasefield = 4 then 99864
when mycasefield = 5 then 99865
when mycasefield = 6 then 99866
when mycasefield = 7 then 99867
when mycasefield = 8 then 99868
when mycasefield = 9 then 99855
when mycasefield = 10 then 99839
end,
alt_min,
alt_max,
longitude,
latitude
(
Select MTB.LocationID
MTB.model_ID
MTB.elevation, --alt min
null, --alt max
MTB.longitude, --longitude
MTB.latitude --latitude
from MyTblB MTB
);

The error I'm getting is:
Incorrect syntax near '='.

I have tried various versions of the case statement based on examples I have found but nothing works.
I would greatly appreciate any assistance with this one. I've been smacking my head against the wall for awhile trying to find a solution.

View 10 Replies View Related

How To Show Records Using Sql Case Statement Or If Else Statement

Feb 20, 2008

i want to display records as per if else condition in ms sql query,for this i have used tables ,queries as follows


as per data in MS Sql

my tables are as follows
1)material
fields are -- material_id,project_type,project_id,qty, --

2)AB_Corporate_project
fields are-- ab_crp_id,custname,contract_no,field_no

3)Other_project
fields are -- other_proj_id,other_custname,po

for ex :
vales in table's are
AB_Corporate_project
=====================
ab_crp_id custname contract_no field_no
1 abc 234 66
2 xyz 33 20

Other_project
============
other_proj_id other_custname po
1 xxcx 111
2 dsd 222

material
=========
material_id project_type project_id qty
1 AB Corporate 1 3
2 Other Project 2 7

i have taken AB Corporate for AB_Corporate_project ,Other Project for Other_project


sample query i write :--

select m.material_id ,m.project_type,m.project_id,m.qty,ab.ab_crp_id,
ab.custname ,op.other_proj_id,op.other_custname,op. po
case if m.project_type = 'AB Corporate' then
select * from AB_Corporate_project where ab.ab_crp_id = m.project_id
else if m.project_type = 'Other Project' then
select * from Other_project where op.other_proj_id=m.project_id
end
from material m,AB_Corporate_project ab,Other_project op


but this query not work,also it gives errors

i want sql query to show data as follows


material_id project_type project_id custname other_custname qty
1 AB Corporate 1 abc -- 3
2 Other Project 2 -- dsd 7

so plz help me how can i write sql query for to show the output
plz send a sql query

View 8 Replies View Related

Trouble With A Select Statement

Sep 12, 2005

lets say i have a table that looks like thisclient   date   amount   account1         5/2/05   100   123451         5/2/05   110   123452         5/2/05   175   223342         5/2/05   10     22334How do I select all clients that have an 80 percent difference in amount for the same account on the same day.  For example, only client 2 would be selected.        

View 1 Replies View Related

Trouble Forming SQL Statement

Sep 28, 2005

Hi there,Probably my problem is very simple with a pretty straightforward answer...but sometimes you get stuck around simple problems and never seem to get out! I have database with 5 fields : 1.RecNo(Pkey,auto)  2.AssetName(not null )  3.AssetNo(null allowed)  4.Description(null allowed)  5.MDAprroval? (null allowed-checkbox)The database already has 500 records I need to frame three different SQL statements to generate results in a datagrid...1. First Query to generate all records which DO NOT have ASSETNO 2. Second query to generate all records which DO HAVE ASSETNO3. Third query to generate all records which HAVE ASSETNO and MDAPPROVAL is checked(or true)I could get a workaoundin the second query but somehow my 'Null' check for Asset No  and where statement in third query is failing.Can someone please post some help with these query formations?Thankyou in advance for all your precious time spent in reading & replying to this post.

View 2 Replies View Related

Subquery Issues In A Select Statement

Nov 28, 2006

Hi there,

I am pulling back records from the DB in this case to get Wheel information. I am pulling back based on user input, but also need to query a second table that contains the Price and model number from another table based on a field being pulled back in the original select.

I am not sure if this makes sense, here is a working copy of the SQL I have , but it's not pretty. There must be another way of stating this statement that i am missing, can anyone give me some suggestiosn?

SELECT tblMacPak2.*,
(SELECT ListPrice
FROM tblMacPakPrices
WHERE WheelId = OEMWheel) AS ListPrice,
(SELECT PartNumber
FROM tblMacPakPrices
WHERE WheelId = OEMWheel) AS PartNumber
FROM tblMacPak2
WHERE (Make = N'honda') AND (Model = N'civic') AND (SubModel = N'standard') AND (YearRange = N'2006') AND (Factory_Wheel_Diameter = N'15')

3 selects in one statement...that can't be right.

Thanks,

View 5 Replies View Related

Update Statement Using A Subquery With Correlation

Apr 18, 2008

Hello

I am new to this forum and pretty new to running queries in SQL Server. I have been doing it for years on an iSeries platform and the following update statement would definitely work in SQL/400....but it does not in SQL Server 2000. Any help would be appreciated.

UPDATE TESTDTA.F0101 X
SET (ABAC07, ABAC12, ABAC28) =
(SELECT AIAC07, AIAC12, AIAC28 FROM TESTDTA.F03012
WHERE AIAN8 = X.ABAN8)
WHERE EXISTS(SELECT AIAC07 FROM TESTDTA.F03012
WHERE AIAN8 = X.ABAN8)

...and here are the errors

Server: Msg 170, Level 15, State 1, Line 1
Line 1: Incorrect syntax near 'X'.
Server: Msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword 'WHERE'.

View 2 Replies View Related

UPDATE Statement: Subquery Returned More Than 1 Value

Oct 3, 2007

I am struggling with syntax for an update statement.
Goal: If a RelationID has invoice history then HasHistory=1


UPDATE [Tbl_Relations]
SET [HasHistory]= 1
FROM [Tbl_Relations] r INNER JOIN
(SELECT RelationID
FROM vw_Invoice_history
GROUP BY RelationID
) inv ON r.RelationID= inv.RelationID

Result: Subquery returned more than 1 value

What am I doing wrong?

Thanks in advance,
Frans

View 9 Replies View Related

Trouble Using Group By Statement With Query

Mar 20, 2007

Hi,
I am having trouble getting my query right. i am using a stored procedure to retrieve this data and bind it to my grid view.
Problem: I can't associate a field with a column that i am returning with my record set.
Details: I have query that i want to return 9 columns (UserName, Pre-Approved, Processing, Underwriting, Conditioned, Approved, Docs Out, Docs Back, Conditions Met). The username column lists all loan agents. I want the other 8 columns to list the name of the borrower (crestline..borrower.lastname)  that is associate with that loan agent and that loan state.  Each time a record is found where there is a valid loan agent (UserName) that meets the 'where' conditions, there will be a borrower. the 'LoanKey' field is a primary key that lets me get the borrower name from the borrower table. I dont know how to construct my query such that those borrower names get associated with their respective column header.
if the query works, my Gridview should look like this ('Name' refers to the borrower name)
UserName | Pre-Approved | Processing | UnderWriting | Conditioned | Approved | Docs Out | Docs Back | Conditions Met 
Bob           |                     |                  |                     |    Name      |                |               |                   |
Bob           |                     |      Name   |                     |                   |                |               |                   |      
Bob           |                     |                  |                     |                   |                |               |      Name    |        
Steve         |                     |                  |      Name      |                   |                |               |                   | 
Steve         |                     |                  |                     |                   |                |    Name  |                   |
 
Here is my sql call: 
SELECT cfcdb..users.username, crestline..borrower.lastname,CASE WHEN crestline..loansp.LoanStatus='Pre-Approved' THEN crestline..loansp.LoanStatus ELSE NULL END AS 'Pre-Approved',CASE WHEN crestline..loansp.LoanStatus='Processing' THEN crestline..loansp.LoanStatus ELSE NULL END AS 'Processing',CASE WHEN crestline..loansp.LoanStatus='Underwriting' THEN crestline..loansp.LoanStatus ELSE NULL END AS 'Underwriting',CASE WHEN crestline..loansp.LoanStatus='Conditioned' THEN crestline..loansp.LoanStatus ELSE NULL END AS 'Conditioned',CASE WHEN crestline..loansp.LoanStatus='Approved' THEN crestline..loansp.LoanStatus ELSE NULL END AS 'Approved',CASE WHEN crestline..loansp.LoanStatus='Docs Out' THEN crestline..loansp.LoanStatus ELSE NULL END AS 'Docs Out',CASE WHEN crestline..loansp.LoanStatus='Docs Back' THEN crestline..loansp.LoanStatus ELSE NULL END AS 'Docs Back',CASE WHEN crestline..loansp.LoanStatus='Conditions Met' THEN crestline..loansp.LoanStatus ELSE NULL END AS 'Conditions Met'FROM cfcdb..usersinner join (crestline..loansp inner join crestline..borrower on crestline..loansp.loankey = crestline..borrower.loankey)on crestline..loansp.fstnamelo=cfcdb..users.firstname AND crestline..loansp.lstnamelo=cfcdb..users.lastnameinner join cfcdb..users_roleson cfcdb..users.username = cfcdb..users_roles.usernamewhere cfcdb..users.active = 1 AND cfcdb..users_roles.groupid = 'agent'AND crestline..loansp.enloanstat <> 'Closed' AND crestline..loansp.enloanstat <> 'Cancelled' AND crestline..loansp.enloanstat <> 'Declined' AND crestline..loansp.enloanstat <> 'On Hold'order by cfcdb..users.username asc
 

View 2 Replies View Related

Trouble With An Insert Into/select Statement

Jan 2, 2008



I have several tables in a database which I always want to update with information from one table with new records (containing contact and demographical information). The setup is something like this:

NewRecordsTable: fn, ln, streetadd, city, emailadd, phonenumber, gender, birthdate

ContactTable: ID(primarykey), fn, ln, streetadd, city, state, zip, phonenumber, email

DemographicTable: ID(linked to primary key ID in Contact table), birthdate, gender


I want to update the ContactTable and DemographicTable with information from the NewRecords Table. What I have done so far is set the identity insert for the ContactTable to on, then inserted the fn, ln, streetadd, email, etc. from the NewTable. This works fine.

I then try to insert ID, birthdate and gender into the DemographicTable where NewRecordsTable.fn=ContactTable.fn AND NRT.ln=CT.ln AND NRT.streetadd=CT.streetadd AND NRT.emailadd=CT.emailadd - This mostly works, but the records which have NULL values any of those fields don't get inserted.

What I really want is to insert the records that have matching email addresses OR matching fn, ln, streetadd combos, but I can't figure out how to get that SELECT/WHERE statement to work.

The problem that underlies this is that I want to insert the ID values from the ContactTable into the DemographicTable, but the only way I can see to make them match properly is by matching the email addresses or fn, ln, streetadd combos from the NewRecordsTable to the ContactTable (all of the email addresses in our NewRecordsTable are unique, unless the person doesn't have an email address, in which case we make sure they have a unique fn, ln, streetadd combo)

Any help would be appreciated,
Thank you!!

View 3 Replies View Related

Subquery Returned More Than 1 Value. This Is Not Permitted When The Subquery Follows =, !=, &<, &<= , &>, &>= Or When The Subquery Is Used As An Expression.

Apr 26, 2008

hello friends.. I am newbie for sql server...I having a problem when executing this procedure .... ALTER PROCEDURE [dbo].[spgetvalues]    @Uid intASBEGIN    SET NOCOUNT ON;        select                                  DATEPART(year, c.fy)as fy,                                                (select contribeamount from wh_contribute where and contribename like 'Retire-Plan B-1%      JRF' ) as survivorship,                (select contribeamount from wh_contribute where and contribename like  'Gross Earnings' and ) as ytdgross,                (select contribeamount from wh_contribute where and contribename like 'Retire-Plan B-1.5%      JRP') as totalcontrib,                                                       from    wh_contribute c                       where    c.uid=@Uid                 Order by fy Asc .....what is the wrong here??  " Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression."please reply asap... 

View 1 Replies View Related

Subquery Returned More Than 1 Value. This Is Not Permitted When The Subquery Follows =, !=, &<, &<= , &>, &>= Or When The Subquery Is Used As An Expression.

Jul 20, 2005

I am getting 2 resultsets depending on conditon, In the secondconditon i am getting the above error could anyone help me..........CREATE proc sp_count_AllNewsPapers@CustomerId intasdeclare @NewsId intset @NewsId = (select NewsDelId from NewsDelivery whereCustomerId=@CustomerId )if not exists(select CustomerId from NewsDelivery whereNewsPapersId=@NewsId)beginselect count( NewsPapersId) from NewsPapersendif exists(select CustomerId from NewsDelivery whereNewsPapersId=@NewsId)beginselect count(NewsDelId) from NewsDelivery whereCustomerid=@CustomeridendGO

View 3 Replies View Related

Trouble Converting SELECT To INSERT Statement

Sep 18, 2005

Trying to convert the following SELECT statement into a INSERT statement and having trouble. No doubt this will be a piece of cake to someone. To eventually get this to a trigger stage would be nice, but for the moment I'd settle for just plain SQL. Using MS SQL 2000. The database name is reporting. The table name is CallLog. I'm trying to convert seperate date (RecvdDate) and time (RecvdTime) columns into a single DateTime column. I've scoured a lot of web pages but I'm still lost.

==============

use reporting
go

SELECT RecvdDate + RecvdTime FROM [dbo].[CallLog]

===============

Any help much appreciated.

View 7 Replies View Related

Random Selection From Table Variable In Subquery As A Column In Select Statement

Nov 7, 2007

Consider the below code: I am trying to find a way so that my select statement (which will actually be used to insert records) can randomly place values in the Source and Type columns that it selects from a list which in this case is records in a table variable. I dont really want to perform the insert inside a loop since the production version will work with millions of records. Anyone have any suggestions of how to change the subqueries that constitute these columns so that they are randomized?




SET NOCOUNT ON


Declare @RandomRecordCount as int, @Counter as int
Select @RandomRecordCount = 1000

Declare @Type table (Name nvarchar(200) NOT NULL)
Declare @Source table (Name nvarchar(200) NOT NULL)
Declare @Users table (Name nvarchar(200) NOT NULL)
Declare @NumericBase table (Number int not null)

Set @Counter = 0

while @Counter < @RandomRecordCount
begin
Insert into @NumericBase(Number)Values(@Counter)
set @Counter = @Counter + 1
end


Insert into @Type(Name)
Select 'Type: Buick' UNION ALL
Select 'Type: Cadillac' UNION ALL
Select 'Type: Chevrolet' UNION ALL
Select 'Type: GMC'

Insert into @Source(Name)
Select 'Source: Japan' UNION ALL
Select 'Source: China' UNION ALL
Select 'Source: Spain' UNION ALL
Select 'Source: India' UNION ALL
Select 'Source: USA'

Insert into @Users(Name)
Select 'keith' UNION ALL
Select 'kevin' UNION ALL
Select 'chris' UNION ALL
Select 'chad' UNION ALL
Select 'brian'


select
1 ProviderId, -- static value
'' Identifier,
'' ClassificationCode,
(select TOP 1 Name from @Source order by newid()) Source,
(select TOP 1 Name from @Type order by newid()) Type

from @NumericBase



SET NOCOUNT OFF

View 14 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved