Simplify (and Correct) A Query
Mar 2, 2006
I’ve got a table called tblApplicant_Details with the following fields - Applicant_ID, Application_ID, Net_Income, Loans.
In this table I’ve got a list of people and their income details (Net_Income) and expenses (loans). In some cases there will be 2 applicants with the same application_ID.
What I need to do is select one applicant (Applicant_ID) per application (Application_ID). In the case of 2 applicants for an application, I need to select the person with the highest income (net_income - loans), if both of the applicants have the same income I want the one with the lowest Applicant_ID and if only one person applies then that person.
Below is the code I’ve been using. I’ve noticed that its not always selecting an applicant for each application. I know it’s also very long for what I am trying to do but I was hoping someone would be able to tell me how I can fix it and tidy it up a bit.
SELECT Application_ID, MIN(Applicant_ID) AS Applicant_ID
FROM (SELECT DERIVEDTBL.Application_ID, dbo.tblAPPLICANT_DETAILS.Applicant_ID
FROM (SELECT MAX(APPLICANT.Net_Income - APPLICANT.Loans) AS Income, APPLICATION.Application_ID
FROM dbo.tblAPPLICANT_DETAILS APPLICANT INNER JOIN
dbo.tblAPPLICATION_DETAILS APPLICATION ON APPLICANT.Application_ID = APPLICATION.Application_ID
GROUP BY APPLICATION.Application_ID) DERIVEDTBL INNER JOIN
dbo.tblAPPLICANT_DETAILS ON DERIVEDTBL.Application_ID = dbo.tblAPPLICANT_DETAILS.Application_ID AND
DERIVEDTBL.Income = dbo.tblAPPLICANT_DETAILS.Net_Income - Loans) DERIVEDTBL
GROUP BY Application_ID
Thanks
View 3 Replies
ADVERTISEMENT
May 27, 2008
Hi all, anyway to simplify this?
SELECT DISTINCT Code_Name, Code_Desc, Code_Reaction_Guide FROM dbo.tbl_ref_OutgoingQA_Control_Limits l, dbo.tbl_ref_SPC_Rules_Code r, dbo.tbl_ref_OutgoingQA_Chart_Type c
WHERE r.Code_Area = 'A' AND r.Test_Type = 'B' AND r.Code_Mode = 'C'
AND r.Code_Name = '1' AND l.Chart_Type_ID = c.Chart_Type_ID AND l.Test_Type = c.Test_Type AND l.Rule1 = 1
UNION
SELECT DISTINCT Code_Name, Code_Desc, Code_Reaction_Guide FROM dbo.tbl_ref_OutgoingQA_Control_Limits l, dbo.tbl_ref_SPC_Rules_Code r, dbo.tbl_ref_OutgoingQA_Chart_Type c
WHERE r.Code_Area = 'A' AND r.Test_Type = 'B' AND r.Code_Mode = 'C'
AND r.Code_Name = '2' AND l.Chart_Type_ID = c.Chart_Type_ID AND l.Test_Type = c.Test_Type AND l.Rule2 = 1
UNION
SELECT DISTINCT Code_Name, Code_Desc, Code_Reaction_Guide FROM dbo.tbl_ref_OutgoingQA_Control_Limits l, dbo.tbl_ref_SPC_Rules_Code r, dbo.tbl_ref_OutgoingQA_Chart_Type c
WHERE r.Code_Area = 'A' AND r.Test_Type = 'B' AND r.Code_Mode = 'C'
AND r.Code_Name = '3' AND l.Chart_Type_ID = c.Chart_Type_ID AND l.Test_Type = c.Test_Type AND l.Rule3 = 1
UNION
SELECT DISTINCT Code_Name, Code_Desc, Code_Reaction_Guide FROM dbo.tbl_ref_OutgoingQA_Control_Limits l, dbo.tbl_ref_SPC_Rules_Code r, dbo.tbl_ref_OutgoingQA_Chart_Type c
WHERE r.Code_Area = 'A' AND r.Test_Type = 'B' AND r.Code_Mode = 'C'
AND r.Code_Name = '4' AND l.Chart_Type_ID = c.Chart_Type_ID AND l.Test_Type = c.Test_Type AND l.Rule4 = 1
UNION
SELECT DISTINCT Code_Name, Code_Desc, Code_Reaction_Guide FROM dbo.tbl_ref_OutgoingQA_Control_Limits l, dbo.tbl_ref_SPC_Rules_Code r, dbo.tbl_ref_OutgoingQA_Chart_Type c
WHERE r.Code_Area = 'A' AND r.Test_Type = 'B' AND r.Code_Mode = 'C'
AND r.Code_Name = '5A' AND l.Chart_Type_ID = c.Chart_Type_ID AND l.Test_Type = c.Test_Type AND l.Rule5A = 1
UNION
SELECT DISTINCT Code_Name, Code_Desc, Code_Reaction_Guide FROM dbo.tbl_ref_OutgoingQA_Control_Limits l, dbo.tbl_ref_SPC_Rules_Code r, dbo.tbl_ref_OutgoingQA_Chart_Type c
WHERE r.Code_Area = 'A' AND r.Test_Type = 'B' AND r.Code_Mode = 'C'
AND r.Code_Name = '5B' AND l.Chart_Type_ID = c.Chart_Type_ID AND l.Test_Type = c.Test_Type AND l.Rule5B = 1
View 1 Replies
View Related
Jul 23, 2005
Hello group!I am having a problem with simplying my query...I would like to get customers' balance info based on how many monthssince they opened their accounts. The tricky part here is accountsstarting with '28' are treated differently than other accounts, theyare given 3 months grace period. In other words, for all otheraccounts, their month0 balance is the balance of their open_month, andmonth1 balance is the balance after the account is opened 1 month, andso on. But accounts starting with '28' month0 balance would be thebalance after the account is opened 3 months, and month1 balance wouldbe the balance after the account is opened 4 months, and so on.My query below works, but since some customers are more than 10 yearsold (more than 120 months), my query is endless! Does anyone know abetter way to do the same job? Many thanks!create table a(person_id int,account int,open_date datetime)insert into a values(1,200001,'11/15/2004')insert into a values(2,280001,'8/20/2004')create table b(account int,balance_date datetime,balance money)insert into b values(200001,'11/30/2004',700)insert into b values(200001,'12/31/2004',800)insert into b values(200001,'1/31/2005',900)insert into b values(200001,'2/28/2005',1000)insert into b values(280001,'8/30/2004',7000)insert into b values(280001,'9/30/2004',8000)insert into b values(280001,'10/31/2004',9000)insert into b values(280001,'11/30/2004',10000)insert into b values(280001,'12/31/2004',15000)insert into b values(280001,'1/31/2005',20000)insert into b values(280001,'2/28/2005',30000)--Ideal output--person_idacc_nomonth0_balancemonth1_balancemonth2_balancemonth3_balance1200000170080090010002280000110000150002000030000select a.person_id,a.account,month0_balance=casewhen a.account like '2%' and a.account not like '28%'thensum(case datediff(mm, a.open_date, balance_date) when 0then b.balance else 0 end)else sum(case datediff(mm, a.open_date, balance_date)when 3 then b.balance else 0 end)end,month1_balance =casewhen a.account like '2%' and a.account not like '28%'thensum(case datediff(mm, a.open_date, balance_date) when 1then b.balance else 0 end)else sum(case datediff(mm, a.open_date, balance_date)when 4 then b.balance else 0 end)endfrom a as ajoin b as bon a.account=b.accountgroup by a.person_id, a.account
View 3 Replies
View Related
Oct 9, 2007
I received the following error today while migrating some code from SQL 2000 standard to SQL 2005 standard:
The query processor ran out of stack space during query optimization. Please simplify the query.
From what I gather, this error is usually an indication that one of the SQL Server 2005 maximum capacity specifications has been exceeded. However, I'm not sure which one. The only one that seems suspect is the number of nested subqueries (32), however I believe the numerous subqueries in my query would be classified as correlated rather than nested.
An example of my code is below. It is necessarily messy, as the output needs to be denormalized somewhat. Note that this runs just fine on SQL 2000, and it retrieves the 1500 or so rows of data in about 30 seconds. Thanks in advance for any ideas as to what may be causing this error. (Sorry for not using code-block, but all the html tags it threw in were exceeding the 50,000 character limit for the message)
BEGIN
SELECT
(SELECT Agent FROM Agent a WHERE a.Card_Number = c.Card_Number AND Agent_Number = 1) AS A5,
(SELECT Agent FROM Agent a WHERE a.Card_Number = c.Card_Number AND Agent_Number = 2) AS A6,
(SELECT Agent FROM Agent a WHERE a.Card_Number = c.Card_Number AND Agent_Number = 3) AS A7,
(SELECT Agent FROM Agent a WHERE a.Card_Number = c.Card_Number AND Agent_Number = 4) AS A8,
dbo.f_formatpseudodate(Accrued_Interest_To) AS AI,
dbo.f_getmiscdescription('AM', c.Card_Number, Amended) AS AM,
Basis_Shareblock_1 AS B1,
Basis_Shareblock_2 AS B2,
Basis_Shareblock_3 AS B3,
Basis_Shareblock_4 AS B4,
Basis AS BS,
dbo.f_getmiscdescription('C1', c.Card_Number, Price_Code_1) AS C1,
dbo.f_getmiscdescription('C2', c.Card_Number, Price_Code_2) AS C2,
dbo.f_getmiscdescription('C3', c.Card_Number, Price_Code_3) AS C3,
dbo.f_getmiscdescription('C4', c.Card_Number, Price_Code_4) AS C4,
dbo.f_getmiscdescription('C5', c.Card_Number, Price_Code_5) AS C5,
dbo.f_getmiscdescription('C6', c.Card_Number, Price_Code_6) AS C6,
CAST(Card_Date AS smalldatetime) AS CD,
c.Card_Number AS CN,
dbo.f_getisocurrencycode(Currency_Code) AS CR,
Card_Status AS CS,
dbo.f_formatpseudodate(Record_Date) AS CT,
Currency_Description AS CU,
(SELECT New_Issue_Description FROM New_Issue ni WHERE ni.Card_Number = c.Card_Number AND New_Issue_Number = 1) AS D1,
(SELECT New_Issue_Description FROM New_Issue ni WHERE ni.Card_Number = c.Card_Number AND New_Issue_Number = 2) AS D2,
(SELECT New_Issue_Description FROM New_Issue ni WHERE ni.Card_Number = c.Card_Number AND New_Issue_Number = 3) AS D3,
(SELECT New_Issue_Description FROM New_Issue ni WHERE ni.Card_Number = c.Card_Number AND New_Issue_Number = 4) AS D4,
(SELECT New_Issue_Description FROM New_Issue ni WHERE ni.Card_Number = c.Card_Number AND New_Issue_Number = 5) AS D5,
(SELECT New_Issue_Description FROM New_Issue ni WHERE ni.Card_Number = c.Card_Number AND New_Issue_Number = 6) AS D6,
dbo.f_formatboolean(Dutch_Auction) AS DA,
dbo.f_formatpseudodate(Dated_Date) AS DD,
dbo.f_getmiscdescription('DI', c.Card_Number, Distribution_In) AS DI,
Dealer_Manager_2 AS DL,
Dealer_Manager_1 AS DM,
dbo.f_getmiscdescription('DV', c.Card_Number, Dividend_In) AS DV,
Basis_Surrender_1 AS E1,
Basis_Receive_1_1 AS E2,
Basis_Amount_1_1 AS E3,
Basis_CUSIP_1_1 AS E4,
Basis_Receive_1_2 AS E5,
Basis_Amount_1_2 AS E6,
Basis_CUSIP_1_2 AS E7,
Basis_Receive_1_3 AS E8,
Basis_Amount_1_3 AS E9,
dbo.f_getmiscdescription('EC', c.Card_Number, Record_Date_Code) AS EC,
Equity_Debt AS ED,
dbo.f_getmiscdescription('EF', c.Card_Number, Effective_Date_Code) AS EF,
dbo.f_getmiscdescription('EX', c.Card_Number, Expiration_Date_Code) AS EX,
dbo.f_getmiscdescription('F1', c.Card_Number, Refer_Code_1) AS F1,
dbo.f_getmiscdescription('F2', c.Card_Number, Refer_Code_2) AS F2,
dbo.f_getmiscdescription('F3', c.Card_Number, Refer_Code_3) AS F3,
dbo.f_formatpseudodate(Effective_Date) AS FD,
File_Activity_Type AS FT,
dbo.f_getmiscdescription('G1', c.Card_Number, Rights_Ratio_1) AS G1,
dbo.f_getmiscdescription('G2', c.Card_Number, Rights_Ratio_2) AS G2,
dbo.f_getmiscdescription('G3', c.Card_Number, Rights_Ratio_3) AS G3,
RTRIM(LTRIM(Original_Card_Number)) AS GC,
dbo.f_getmiscdescription('GD', c.Card_Number, Ex_Rights_Date_Code) AS GD,
dbo.f_getmiscdescription('GT', c.Card_Number, Rights_To) AS GT,
Basis_Amount_2_3 AS H1,
Basis_CUSIP_2_3 AS H2,
Basis_Surrender_3 AS H3,
Basis_Receive_3_1 AS H4,
Basis_Amount_3_1 AS H5,
Basis_CUSIP_3_1 AS H6,
Basis_Receive_3_2 AS H7,
Basis_Amount_3_2 AS H8,
Basis_CUSIP_3_2 AS H9,
Information_Agent_1 AS I1,
Information_Agent_2 AS I2,
Interest_Rate AS [IN],
dbo.f_getmiscdescription('J1', c.Card_Number, Subscription_Ratio_Code_1) AS J1,
dbo.f_getmiscdescription('J2', c.Card_Number, Subscription_Ratio_Code_2) AS J2,
dbo.f_getmiscdescription('J3', c.Card_Number, Subscription_Ratio_Code_3) AS J3,
Basis_CUSIP_4_2 AS K1,
Basis_Receive_4_3 AS K2,
Basis_Amount_4_3 AS K3,
Basis_CUSIP_4_3 AS K4,
Basis_Receive_3_3 AS L1,
Basis_Amount_3_3 AS L2,
Basis_CUSIP_3_3 AS L3,
Basis_Surrender_4 AS L4,
Basis_Receive_4_1 AS L5,
Basis_Amount_4_1 AS L6,
Basis_CUSIP_4_1 AS L7,
Basis_Receive_4_2 AS L8,
Basis_Amount_4_2 AS L9,
dbo.f_formatpseudodate(Withdrawal_After) AS LA,
dbo.f_getmiscdescription('LC', c.Card_Number, Withdrawal_After_Code) AS LC,
dbo.f_getmiscdescription('LG', c.Card_Number, Eligibility) AS LG,
Withdrawal_After_Time AS LT,
dbo.f_getmiscdescription('LZ', c.Card_Number, Withdrawal_After_Zone) AS LZ,
Option_Expiration_Time AS M1,
Rights_Expire_Time AS M3,
Expiration_Date_Time AS M4,
dbo.f_formatpseudodate(Maturity_Date) AS MD,
Maximum_Eligibility AS ME,
dbo.f_validatecardnumber(Refer_Card_1) AS N1,
dbo.f_validatecardnumber(Refer_Card_2) AS N2,
dbo.f_validatecardnumber(Refer_Card_3) AS N3,
dbo.f_getmiscdescription('NT', c.Card_Number, Interest_Rate_Code) AS NT,
DTC_Match_Card_Number AS O3,
Offer_By AS OB,
Odd_Lot AS OD,
dbo.f_getmiscdescription('OV', c.Card_Number, OverSubscription) AS OV,
dbo.f_formatpseudodate(Option_Expiration_Date) AS OX,
(SELECT Agent_Telephone FROM Agent a WHERE a.Card_Number = c.Card_Number AND Agent_Number = 4) AS P1,
Information_Agent_Telephone_1 AS P2,
Information_Agent_Telephone_2 AS P3,
Dealer_Manager_Telephone_1 AS P4,
Dealer_Manager_Telephone_2 AS P5,
CUSIP_Number AS PN,
dbo.f_formatpseudodate(Pro_Ration_Date) AS PO,
dbo.f_getmiscdescription('PY', c.Card_Number, Payable_To) AS PY,
dbo.f_getmiscdescription('PZ', c.Card_Number, Protect_Period) AS PZ,
Price_1 AS R1,
Price_2 AS R2,
Price_3 AS R3,
Price_4 AS R4,
Price_5 AS R5,
Price_6 AS R6,
dbo.f_getmiscdescription('RB', c.Card_Number, Rights_Transferable) AS RB,
Rights_CUSIP AS RC,
Issuer_Description AS RD,
dbo.f_getmiscdescription('RI', c.Card_Number, Pro_Ration_Date_Code) AS RI,
Record_Type AS RT,
dbo.f_formatpseudodate(Rights_Expire_Date) AS RX,
CAST(Subscription_Ratio_1 AS varchar(12)) + Subscription_Ratio_1_Unit AS S1,
CAST(Subscription_Ratio_2 AS varchar(12)) + Subscription_Ratio_2_Unit AS S2,
CAST(Subscription_Ratio_3 AS varchar(12)) + Subscription_Ratio_3_Unit AS S3,
dbo.f_getmiscdescription('SC', c.Card_Number, Source_Name) AS SC,
Service_Type AS SE,
dbo.f_getmiscdescription('ST', c.Card_Number, Subscription_To) AS ST,
(SELECT Redemption_Agent_Telephone FROM Redemption_Agent ra WHERE ra.Card_Number = c.Card_Number AND Redemption_Agent_Number = 1) AS T2,
(SELECT Redemption_Agent_Telephone FROM Redemption_Agent ra WHERE ra.Card_Number = c.Card_Number AND Redemption_Agent_Number = 2) AS T3,
(SELECT Redemption_Agent_Telephone FROM Redemption_Agent ra WHERE ra.Card_Number = c.Card_Number AND Redemption_Agent_Number = 3) AS T4,
(SELECT Redemption_Agent_Telephone FROM Redemption_Agent ra WHERE ra.Card_Number = c.Card_Number AND Redemption_Agent_Number = 4) AS T5,
(SELECT Agent_Telephone FROM Agent a WHERE a.Card_Number = c.Card_Number AND Agent_Number = 1) AS T7,
(SELECT Agent_Telephone FROM Agent a WHERE a.Card_Number = c.Card_Number AND Agent_Number = 2) AS T8,
(SELECT Agent_Telephone FROM Agent a WHERE a.Card_Number = c.Card_Number AND Agent_Number = 3) AS T9,
Tickler_Date AS TK,
dbo.f_getmiscdescription('TP', c.Card_Number, To_Purchase) AS TP,
dbo.f_getmiscdescription('TS', c.Card_Number, Transaction_Status) AS TS,
dbo.f_gettxtext(c.Card_Number) AS TX,
Basis_CUSIP_1_3 AS U1,
Basis_Surrender_2 AS U2,
Basis_Receive_2_1 AS U3,
Basis_Amount_2_1 AS U4,
Basis_CUSIP_2_1 AS U5,
Basis_Receive_2_2 AS U6,
Basis_Amount_2_2 AS U7,
Basis_CUSIP_2_2 AS U8,
Basis_Receive_2_3 AS U9,
RTRIM(Issue_Description) AS UD,
Voluntary_Mandatory AS VM,
(SELECT New_Issue_CUSIP FROM New_Issue ni WHERE ni.Card_Number = c.Card_Number AND New_Issue_Number = 1) AS W1,
(SELECT New_Issue_CUSIP FROM New_Issue ni WHERE ni.Card_Number = c.Card_Number AND New_Issue_Number = 2) AS W2,
(SELECT New_Issue_CUSIP FROM New_Issue ni WHERE ni.Card_Number = c.Card_Number AND New_Issue_Number = 3) AS W3,
(SELECT New_Issue_CUSIP FROM New_Issue ni WHERE ni.Card_Number = c.Card_Number AND New_Issue_Number = 4) AS W4,
(SELECT New_Issue_CUSIP FROM New_Issue ni WHERE ni.Card_Number = c.Card_Number AND New_Issue_Number = 5) AS W5,
(SELECT New_Issue_CUSIP FROM New_Issue ni WHERE ni.Card_Number = c.Card_Number AND New_Issue_Number = 6) AS W6,
dbo.f_formatpseudodate(Withdrawal_Prior_To) AS WD,
Withdrawal_Prior_To_Time AS WH,
dbo.f_getmiscdescription('WO', c.Card_Number, Withdrawal_Prior_To_Code) AS WO,
dbo.f_getmiscdescription('WZ', c.Card_Number, Withdrawal_Prior_To_Zone) AS WZ,
(SELECT Payable_Rate_Amount FROM Payable_Rate pr WHERE pr.Card_Number = c.Card_Number AND Payable_Rate_Number =3) AS X1,
(SELECT Payable_Rate_CUSIP FROM Payable_Rate pr WHERE pr.Card_Number = c.Card_Number AND Payable_Rate_Number = 3) AS X2,
dbo.f_formatpseudodate(Expiration_Date) AS XD,
dbo.f_formatpseudodate(Ex_Rights_Date) AS XR,
dbo.f_getmiscdescription('XT', c.Card_Number, Rights_Expire_Code) AS XT,
Payable_Rate_Shareblock AS Y1,
Payable_Rate_Surrender AS Y2,
(SELECT Payable_Rate_Receive FROM Payable_Rate pr WHERE pr.Card_Number = c.Card_Number AND Payable_Rate_Number =1) AS Y3,
(SELECT Payable_Rate_Amount FROM Payable_Rate pr WHERE pr.Card_Number = c.Card_Number AND Payable_Rate_Number =1) AS Y4,
(SELECT Payable_Rate_CUSIP FROM Payable_Rate pr WHERE pr.Card_Number = c.Card_Number AND Payable_Rate_Number =1) AS Y5,
(SELECT Payable_Rate_Receive FROM Payable_Rate pr WHERE pr.Card_Number = c.Card_Number AND Payable_Rate_Number =2) AS Y6,
(SELECT Payable_Rate_Amount FROM Payable_Rate pr WHERE pr.Card_Number = c.Card_Number AND Payable_Rate_Number =2) AS Y7,
(SELECT Payable_Rate_CUSIP FROM Payable_Rate pr WHERE pr.Card_Number = c.Card_Number AND Payable_Rate_Number =2) AS Y8,
(SELECT Payable_Rate_Receive FROM Payable_Rate pr WHERE pr.Card_Number = c.Card_Number AND Payable_Rate_Number =3) AS Y9,
dbo.f_formatpseudodate(Payment_Date) AS YD,
dbo.f_getmiscdescription('YR', c.Card_Number, Payable_Rate) AS YR,
dbo.f_getmiscdescription('Z1', c.Card_Number, Option_Expiration_Zone) AS Z1,
Rights_Expire_Zone AS Z3,
Expiration_Date_Zone AS Z4
FROM COMMON c
INNER JOIN DC_DailyCard dc ON c.Card_Number = dc.Card_Number
WHERE c.Card_Status = 'R' AND c.Card_Date BETWEEN @start_date AND @end_date
END
View 2 Replies
View Related
Nov 6, 2007
SELECT WRREGN,WRCONO,WRDESC,WRWH01 as "WRWHSE", 1 as "WRORDER", WRDTMT
FROM PPTREASUSA.WHREGN
WHERE RTRIM(WRWH01)<>''
UNION
SELECT WRREGN,WRCONO,WRDESC,WRWH02 as "WRWHSE", 2 as "WRORDER", WRDTMT
FROM PPTREASUSA.WHREGN
WHERE RTRIM(WRWH02)<>''
.
.
.
.
.
UNION
SELECT WRREGN,WRCONO,WRDESC,WRW100 as "WRWHSE", 100 as "WRORDER", WRDTMT
FROM PPTREASUSA.WHREGN
WHERE RTRIM(WRW100)<>''
I have 100 queries pretty similar. Can I write one query for all instead?. How could I simplify this process? Using a cursor?
http://www.sqlserverstudy.com
View 12 Replies
View Related
Oct 11, 2007
I have the following where clause below which works fine. However, I have not been advised that the client also requires the range of codes: 1400-2089 and 2100-2299 which do not lend themselves readily to the IN statement.
I realize I could add yet another OR statement, however, I would prefer to simplify this query without it getting larger and larger with future request. Can someone suggest a better query?
Where
(DischDate between '2006-11-01' and '2007-09-30' And
PrinDxCode
IN ('042','140','2089','2031','2051','2100','2299','2300',
'2349','2350','2389','2390','2399','2732','2733','2849',
'2850','2883','2898','V073','V078','V100','V109','V580',
'V581','V661','V662','V671','V672','V711','V760','V769'))
Or (DischDate between '2006-11-01' and '2007-09-30' And
SecDx1Code
IN ('042','140','2089','2031','2051','2100','2299','2300',
'2349','2350','2389','2390','2399','2732','2733','2849',
'2850','2883','2898','V073','V078','V100','V109','V580',
'V581','V661','V662','V671','V672','V711','V760','V769'))
View 15 Replies
View Related
Jan 20, 2005
Dear Reader(s),
Is there anyway to write the following stored procedure without the loop so that it goes much faster? :confused:
----------------------------------------------------------------------------
use MJ_ReportBase
go
if exists(select 1 from sysobjects where type='P' and name='sp_Periode')
begin
drop procedure sp_Periode
end
go
create procedure sp_Periode
@start int
, @stop int
as
declare @x int
set @x = 0
set @x=@start
delete from tbl_periode
while (@x>=@stop)
begin
-- ---
-- ---
-- Create table tbl_inout
if exists(select 1 from sysobjects where type='U' and name='tbl_inout')
begin
drop table tbl_inout
end
select datetimestamp,accname,badgeid,personname,inoutreg into tbl_inout from WinXS..x18 where convert(varchar,datetimestamp,120)+' '+ltrim(str(id))+' '+ltrim(str(badgeid)) in
(select convert(varchar,max(datetimestamp),120)+' '+ltrim(str(max(id)))+' '+ltrim(str(badgeid)) as datetimestamp from WinXS..x18 where (accname='Kelder -1' or accname='Tnk Entree') and convert(varchar,datetimestamp,105)=convert(varchar ,getdate()-abs(@x),105) group by badgeid)
and badgeid>0
order by personname
-- ---
-- ---
-- Create table tbl_result
if exists(select 1 from sysobjects where type='U' and name='tbl_result')
begin
drop table tbl_result
end
-- ---
-- ---
select
convert(varchar,datetimestamp,105) 'DATUM'
, badgeid 'PAS'
, initials 'VOORNAAM'
, personname 'NAAM'
, convert(varchar,min(datetimestamp),108) 'MIN'
, convert(varchar,max(datetimestamp),108) 'MAX'
into
tbl_result
from
WinXS..x18
where
convert(varchar,datetimestamp,105)=convert(varchar ,getdate()-abs(@x),105)
and
accname in ('Kelder -1','Tnk Entree')
and badgeid>0
group by
convert(varchar,WinXS..x18.datetimestamp,105)
, badgeid
, initials
, personname
order by
initials
, personname asc
, convert(varchar,datetimestamp,105) asc
-- ---
-- ---
-- Rapportage tabel
insert into
tbl_periode
select
tbl_result.datum as DATUM
, ltrim(ltrim(rtrim(tbl_result.naam))+' '+ltrim(rtrim(isnull(tbl_result.voornaam,' ')))) as NAAM
, tbl_result.min as MIN
, tbl_result.max as MAX
, case tbl_inout.inoutreg when 1 then 'in' when 2 then 'out' else 'err' end as [IN/OUT]
, substring('00000',1,5-len(tbl_result.pas))+ltrim(str(tbl_result.pas)) as PAS
from
tbl_inout,tbl_result
where
tbl_result.datum+' '+tbl_result.max+' '+ltrim(str(tbl_result.pas))
= convert(varchar,tbl_inout.datetimestamp,105)+' '+convert(varchar,tbl_inout.datetimestamp,108)+' '+ltrim(str(badgeid))
order by
tbl_result.naam asc
-- ---
-- ---
--
set @x=@x-1
end
go
print 'Klaar!'
--------------------------------------------------------------------------
What it does is determining the minimum entry time and the maximum exiting time per day of people going true the main entrance of a building.
Many thanks in advance.
:)
View 3 Replies
View Related
Sep 29, 2007
DECLARE @fullname nvarchar(50)
SET @fullname =
(SELECT (OriginalName + ContentType) AS Name
FROM Files_Dyn)
INSERT
INTO Files_Dyn(FullName)
VALUES (@fullname) where username = 'user_admin'
...what is the wrong with this query..it is giving 'Incorrect syntax near the keyword 'where'. Please correct me!
thanks in advance!
View 10 Replies
View Related
Jun 2, 2008
hi!
select min(dbo.FS_ItemInventory.Bin) from
(SELECT MIN(dbo.FS_LotTrace.LotNumber),dbo.FS_ItemInventory.Bin FROM
dbo.FS_LotTrace RIGHT OUTER JOIN dbo.FS_MOHeader AS h INNER JOIN
dbo.FS_MOLine AS l ON l.MOHeaderKey = h.MOHeaderKey INNER JOIN
dbo.FS_Item AS i ON i.ItemKey = l.ItemKey INNER JOIN
dbo.FS_MOLineData ON l.MOLineKey = dbo.FS_MOLineData.MOLineKey LEFT OUTER JOIN
dbo.FS_DemandSupply AS ds ON l.MOLineKey = ds.TopLevelDemandSupplyKey LEFT OUTER JOIN
dbo.FS_ItemInventory RIGHT OUTER JOIN
dbo.FS_Item AS di ON dbo.FS_ItemInventory.ItemKey = di.ItemKey on ds.DemandItemKey = di.ItemKey on
dbo.FS_LotTrace.LotTraceKey = dbo.FS_ItemInventory.LotTraceKey
where (dbo.FS_ItemInventory.InventoryCategory!='H' or dbo.FS_ItemInventory.InventoryCategory is null) group by di.ItemNumber,dbo.FS_ItemInventory.Bin)
when i tried this query,
i get a error like
Incorrect syntax near ')'
pls provide the correct query for this.
reg,
s.srini
View 3 Replies
View Related
Jun 2, 2008
hi!
select min(dbo.FS_ItemInventory.Bin) from
(SELECT MIN(dbo.FS_LotTrace.LotNumber),dbo.FS_ItemInventory.Bin FROM
dbo.FS_LotTrace RIGHT OUTER JOIN dbo.FS_MOHeader AS h INNER JOIN
dbo.FS_MOLine AS l ON l.MOHeaderKey = h.MOHeaderKey INNER JOIN
dbo.FS_Item AS i ON i.ItemKey = l.ItemKey INNER JOIN
dbo.FS_MOLineData ON l.MOLineKey = dbo.FS_MOLineData.MOLineKey LEFT OUTER JOIN
dbo.FS_DemandSupply AS ds ON l.MOLineKey = ds.TopLevelDemandSupplyKey LEFT OUTER JOIN
dbo.FS_ItemInventory RIGHT OUTER JOIN
dbo.FS_Item AS di ON dbo.FS_ItemInventory.ItemKey = di.ItemKey on ds.DemandItemKey = di.ItemKey on
dbo.FS_LotTrace.LotTraceKey = dbo.FS_ItemInventory.LotTraceKey
where (dbo.FS_ItemInventory.InventoryCategory!='H' or dbo.FS_ItemInventory.InventoryCategory is null) group by di.ItemNumber,dbo.FS_ItemInventory.Bin)
when i tried this query,
i get a error like
Incorrect syntax near ')'
pls provide the correct query for this.
reg,
s.srini
View 1 Replies
View Related
Feb 6, 2006
Hello.
I am new at SQL and am using SQL server express edition and im a bit stuck! I am using ASP.NET and C# in my website which is using sql database back end.
String SQLroom = "SELECT DISTINCT RoomName FROM Room INNER JOIN RoomCalendar ON Room.RoomID = RoomCalendar.RoomID WHERE Capacity = '" + reqCapacity + "' " + " AND NOT ('" + newRoomEnd + "' <= roomStartDateTime OR '" + newRoomStart + "' >= roomEndDateTime) AND (OHP = '" + ohpYesNo + "' AND AV = '" + avYesNo + "') ";
This is my SQL string... what it is trying to do is:
find the room
where the capacity is the reqcapacity entered by user
and the startdatetime and enddatetime entered by the user are not present in the table for that room capacity
and then look at whether the user requires OHP or AV facilities, which are stored in the database as either yes or no values.
The problem i am having is with the condition in the sql query... because the user may require an OHP and not AV, but then the room returned "`could" have AV facilities, as it wouldnt make a difference to them if it was there or not, basically, the yes condition has to be satisfied.
Not sure whether i should be using AND, or OR? or a combination.
Any ideas gratefully appreciated....
Sandy
View 2 Replies
View Related
Jan 3, 2008
1 SELECT distinct A.EAIndex,
2 A.ChainCode AS ChainCode,
3 A.JobDate,
4 C.BillerName,
5 B.BusinessCode,
6 D.ChainName,
7 A.BillBegDate,
8 A.BillEndDate,
9 A.PostDate,
10 A.BillCount,
11 A.ChAmount,
12 A.PostAmount,
13 A.ProChargeFee,
14 A.BalanceStatus AS BalanceStatus,
15 B.BillerInfoCode AS BillerInfoCode ,
16 CONVERT(varchar(10), A.BalanceDate, 112)BalanceDate,
17 A.AdjustDate,
18 C.BillerCode ,
19 (a.ChAmount- a.ProChargeFee) AS Fee,
20 E.EABillerCode, E.RelAdjustDate
21 FROM ZT_EAccount A
22 Inner Join ZT_BillerInfo B On Right('00000'+Rtrim(Ltrim(A.BillerCode)),5) = Right('00000'+Rtrim(Ltrim(B.BillerInfoCode)),5)
23 Inner Join ZT_Biller C ON B.ParentCode = C.BillerCode
24 Inner Join ZT_Chain D On A.ChainCode = D.ChainCode
25 Inner Join ZT_EAccountAdjust E ON a.EAIndex=E.EAIndex and a.BillerCode=E.BusCode
26 Where A.JobDate BETWEEN '20071001' AND '20071005' AND C.CompanyCode='533'
In line 13 I want to add a Query to make sure if ZT_BillerInfo.Rmflag = 1, if it's =1 then ProChargeFee =0if ZT_BillerInfo.RmFlag =0 , then ProChargeFee = a.ProChargeFee.I add this line �Case B.RmFlag = '1' then 0 else A.ProChargeFee 】instead of Line 13 (A.ProChargeFee)but I execute Sql I got error message on the line I have jsut modified..can you please help me to know why and how to correct it? thank you very much
View 4 Replies
View Related
Feb 26, 2008
Hi all,
I have written a query which is not producing the correct ouput.
Please help me to solve the query issue.
my query goes like this:-
SELECT ResourceInformation.PreferredFirstName, ResourceInformation.PreferredLastName, ResourceInformation.CellPhone,
ResourceInformation.HomePhone, ResourceInformation.HomeAddressLine1, ResourceInformation.HomeAddressLine2,
ResourceInformation.HomeAddressState,ResourceInformation.HomeAddressCity,ResourceInformation.HomeAddressZIP,
ResourceInformation.HomeAddressCountry, EmploymentInformation.ArrangementType, EmploymentInformation.PracticeGroup, Projects.Recruiter,
Projects.AccountManager, Projects.TEPOApproved, Projects.BillRate, Projects.Expenses, Projects.ClientProjMgr,
Projects.ClientAddressLine1,Projects.ClientAddressLine2,Projects.ClientAddressCity,Projects.ClientAddressZIP,Projects.ClientAddressState,
Projects.ClientAddressCountry,Projects.LabourCategoryNotes, Projects.Client, Projects.EndClient, Projects.ProjectStartDate,
Projects.DrugScreenRequired, Projects.SkillSet, Projects.AribaProposal, Projects.Sourcer, Projects.ProjectEndDate, Subtier.SubtierCompany,
Subtier.SubtierContactName, Subtier.SubtierAddressLine1,Subtier.SubtierAddressLine2,Subtier.SubtierAddressCity,Subtier.SubtierAddressState,
Subtier.SubtierAddressZIP,Subtier.SubtierAddressCountry, Subtier.SubtierEmail, Subtier.SubtierPhone, Subtier.TaxID,
Subtier.SubtierVendorPassthrough, Subtier.ClientPassthrough, Compensation.PaymentTerms
FROM ResourceInformation INNER JOIN
EmploymentInformation ON ResourceInformation.ResourceID = EmploymentInformation.ResourceID CROSS JOIN
Projects CROSS JOIN
Subtier CROSS JOIN
Compensation
WHERE (Projects.EmploymentID = 23) AND (ResourceInformation.ResourceID = 23)
View 1 Replies
View Related
Jan 3, 2008
I'm using AVG in a simple query but the results are being returned as INTEGERs and not the correct DOUBLE form.
AVG is being used on integer fields in a .mdf database eg: "SELECT AVG(intField) AS Results FROM myDB"
Thanks,
Geoff
View 1 Replies
View Related
Nov 10, 2003
I have the following .bat file that I call to register users to my MSDE instance...
echo osql -E -S %COMPUTERNAME%OfficiumInstance -Q "sp_grantlogin '" + %COMPUTERNAME% + "ASPNET'"
echo osql -E -S %COMPUTERNAME%OfficiumInstance -d Officium -Q "sp_grantdbaccess '" + %COMPUTERNAME% + "ASPNET'"
echo osql -E -S %COMPUTERNAME%OfficiumInstance -d Officium -Q "sp_addrolemember 'db_owner', '" + %COMPUTERNAME% + "ASPNET'"
My question is how do I correctly append %COMPUTERNAME% as a string to
I have tried using + signs...
"sp_grantlogin '" + %COMPUTERNAME% + "ASPNET'"
But that doesn't work.
I have looked for .bat file tutorials on the web but can't find the correct way to do this.
Greg
View 1 Replies
View Related
Jul 5, 2007
Hi,
I am using SqlCacheDependency with the query notifications of SQL server 2005.
It is working nicely with the dbo.owner account but not with my web user account,
so I am thinking something is wrong with the permissions.
After searching around, it seems that the main permissions to enable are these:
GRANT SUBSCRIBE QUERY NOTIFICATIONS TO theAccount
GRANT RECEIVE ON QueryNotificationErrorsQueue TO theAccount
GRANT REFERENCES on CONTRACT::[http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification] to theAccount
GRANT SELECT TO theAccount.
I enabled these and it still doesn't work. When I change my table, my cache is not getting invalidations.
Does anyone know what could be going on? Or perhaps how can I trace the problem and get some clues?
thanks so much,
-tajmahal
View 3 Replies
View Related
May 22, 2015
DECLARE @DBEngineLogin VARCHAR(100)
DECLARE @AgentLogin VARCHAR(100)
EXECUTE master.dbo.xp_instance_regread
@rootkey = N'HKEY_LOCAL_MACHINE',
@key = N'SYSTEMCurrentControlSetServicesMSSQLServer',
@value_name = N'ObjectName',
@value = @DBEngineLogin OUTPUT
[Code] ....
Query to get the exact servername ( do not want to use @@servername), either need to use registry to read or using DMV...
View 3 Replies
View Related
Nov 22, 2005
I've created C#.net program (behind code style).
when I run it in Internet explorer, the following error occurs in IE window.
pls instruct me how to handle and correct this error.
And how to initialize the connectionstring... Great thank!
Server Error in '/' Application.
--------------------------------------------------------------------------------
The ConnectionString property has not been initialized. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The ConnectionString property has not been initialized.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidOperationException: The ConnectionString property has not been initialized.] System.Data.SqlClient.SqlConnection.Open() +809 CodeBox.BehindCode.getSubject() +80 CodeBox.BehindCode.Page_Load(Object sender, EventArgs e) +31 System.Web.UI.Control.OnLoad(EventArgs e) +67 System.Web.UI.Control.LoadRecursive() +29 System.Web.UI.Page.ProcessRequestMain() +724
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:1.0.3705.0; ASP.NET Version:1.0.3705.0
View 5 Replies
View Related
Oct 16, 2000
I have a simple while process to use with a trigger to insert values
into another table. IN VB this was simple but the while in TSQL seems
a little different. If anyone can point out my flaw greatly appreciated.
while @cnter < @nodays
--insert values
insert into table values (value1, value2)
--then increment counters and repeat
set @sdate = @sdate + 1
Set @cnter = @cnter + 1
How or what is the best way to loop back?
View 2 Replies
View Related
Mar 4, 2001
If you start receiving continuous error messages by e-mail indicating that the transaction log is full. After 2 days, the messages suddenly stopped. What could be the reason?
Windows NT App log is full or SQL Server Agent stopped
I think SQL Server Agent stopped
How do you think..and why ?
thanks
View 2 Replies
View Related
Mar 5, 2001
If you start receiving continuous error messages by e-mail indicating that the transaction log is full. After 2 days, the messages suddenly stopped. What could be the reason?
Windows NT App log is full or SQL Server Agent stopped
I think SQL Server Agent stopped
How do you think..and why ?
thanks
View 1 Replies
View Related
Apr 24, 2008
Im new to SQL so please bear with me & help me as to why Im not getting the desired results.
I want to find the difference between two sets of tables that reside in different databases but contain the same data.
I ONLY WANT
a. records that are only in A but not in B
b. records that are only in B but not in A
______________________________________________________________________
Here is what I wrote using something that I found in this forum -
CREATE PROCEDURE RPT_DETAILS
AS
BEGIN
DECLARE @Rowcount AS INT
DECLARE @First_Name AS VARCHAR(50)
DECLARE @Last_Name AS VARCHAR(50)
DECLARE @Id AS INT
CREATE TABLE #Prowess(ID INT NOT NULL, First_Name VARCHAR(50), Last_Name VARCHAR(50))
CREATE TABLE #SDK(ID INT NOT NULL, First_Name VARCHAR(50), Last_Name VARCHAR(50))
INSERT INTO #Prowess
SELECT bb.beenumber, be.FirstName, be.LastName FROM beebusiness bb
join beeentity be on bb.beebusinessguid = bb.beebusinessguid
INSERT INTO #SDK
SELECT cast(sa_ss as INT), first_name, last_name from ml
SELECT @ROWCOUNT = MAX(ID) FROM #SDK
PRINT '------------------------------------------------------------------------------------------'
PRINT '------------------------COMPARISION REPORT Between Prowess & SDK--------------------------'
PRINT '------------------------------------------------------------------------------------------'
PRINT 'TOTAL Difference ('+ +
CAST(@ROWCOUNT AS VARCHAR(50))
WHILE @ROWCOUNT > 0
BEGIN
SELECT @First_Name = First_name, @Last_Name = Last_name, @ID = ID
FROM #Prowess WHERE ID = @ROWCOUNT
PRINT ' * '+@First_Name+@Last_Name
SET @ROWCOUNT = @ROWCOUNT - 1
END
SELECT @ROWCOUNT = MAX(ID) FROM #Sdk
PRINT 'TOTAL Difference ('+ + CAST(@ROWCOUNT AS VARCHAR(50))
WHILE @ROWCOUNT > 0
BEGIN
SELECT @First_Name = First_name, @Last_Name = Last_name, @ID = ID
FROM #Sdk WHERE ID = @ROWCOUNT
PRINT ' * '+@First_Name+@Last_Name
SET @ROWCOUNT = @ROWCOUNT - 1
END
DROP TABLE #Prowess
DROP TABLE #Sdk
END
View 5 Replies
View Related
May 5, 2008
declare @var varchar(50)
set @var= 'COLUMNNAME'
select ID, a.@var , b.@var
from rooper a
join jim_rooper b on b.id = a.id
join b_rooper bb on bb.id = a.id
where a.@var != b.@var
All that Im trying to do here is instead of using a columnname, Im trying to substitute it with a variable so that it can be referenced at multiple places...
View 4 Replies
View Related
May 28, 2008
Hi
I am writing T-SQL pls tell me wheather it is correct syntax or not
DECLARE @Chg1 VARCHAR(500)
SET @Chg1 = 'declare @AntID numeric exec casp_Switch_BackupData @AntID = #ANTID#'
SET @Chg1 = REPLACE(@Chg1,'#ANTID#','@AntID')
EXEC (@Chg1)
As I am getting following output
Command(s) completed successfully.
T.I.A
View 6 Replies
View Related
Jun 2, 2008
hi!
i want to use IN query like
select ... from ...
where field1 in (...)
and field2 in (....)
when i write query like this, the result is display.
but its wrong.
is it correct?
View 3 Replies
View Related
Aug 29, 2005
Dim strsql As String
strsql = "insert into MYENTRY(entryid) "
strsql &= "VALUES ("
strsql &= "'" & strtheEntryid & ")' "
I am not sure if this is correct snytax?
View 3 Replies
View Related
Jun 28, 2006
hi
if row.col1 = nothing then ...
instead of (sql2k) if dtssource("col1") = null then...
TIA
View 3 Replies
View Related
Jan 1, 2008
Hello to all,
Is it correct way to register my CLR library instead of having T-SQL codes (eg, Strored Procedure, Functions and Triggers) in the database in the following case:
Code security: If my Application (in .NET 2.0) and SQL Server Express in same PC and I have to give Windows-Administrator password to my application-user (to install/unistall some other softwares)
Thanks
PSDCHD
View 1 Replies
View Related
Sep 25, 2006
HelloI have having trouble displaying some simple columns in ascending order.I know that the database is populated and I can get the more complex code to work if I display like this: SELECT FName, LName, Town, '<a href="' + url + '">' + Site + '</a>' as LinkFROM Names_DBWHERE FName = 'Tom' And url like 'http:%'ORDER BY LName ASCBut I need a simpler view but I can't get it to workI have tried this:SELECT FName, LNameFROM Names_DBORDER BY LName ASCAnd thisSELECT FName, LNameFROM Names_DBORDER BY LName ASC; And This:SELECT FName, LNameFROM Names_DBORDER BY LName 'ASC' What is wrong with this syntax?ThanksLynn
View 2 Replies
View Related
May 12, 2008
I'm trying to get a year count and a year amount of payments made by a client. Below is my statement, it is not giving a correct count. If a client made more than one payment on the same day it counts it as 1.
What can I do to this statement to get correct totals?
SELECT DISTINCT Client_ID, DATEPART(year,PaymentDate) AS 'Year', SUM(AmountPaid) AS 'TotalYearlyPayments', COUNT(DISTINCT Payment_ID) AS 'YearlyPaymentCount'FROM tblPaymentsWHERE Client_ID = @ClientIDGROUP BY Client_ID, DATEPART(year, PaymentDate)ORDER BY Client_ID, Year
View 1 Replies
View Related
Jun 5, 2006
Hi, I'm building a web application in which I want to prevent SQL injection. I'm using stored procedures, and using queries on my app like this:in my database...create proc createStudy@title varchar(200),@text textasinsert into studies values(@title,@text)goand in my web app...query="createStudy '"+titleBox.Text+"','"+textBox.Text+"'"; //title and text boxes are textboxes, createStudy is a stored procedure in my databaseodmccommand cmd = new odbccommand(query,con);con.Open();cmd.ExecuteNonQuery();But before this I do this code:if (titleBox.Text.Contains("Drop") || titleBox.Text.Contains("Delete")) messageLabel.Text="No permissions to do that";else(...my code)Is this ok to prevent SQL injection?!?
View 5 Replies
View Related
Aug 13, 2004
Hi,
This is strange....
I am getting my source data from another system am storing the SaleAmount of each product in a field the data type of which is [decimal](12, 2).
For some products I am getting an exact match (upto 2 decimal places) as compared with my source data BUT for some other products the value before the decimal places is correct but the 2 digits after the decimal place does not match with the source data :confused:
Even if this sounds stupid, can you please guide me. Am i missing some very basic and common sense thing?
Many TIA.
View 2 Replies
View Related
Mar 15, 2007
I have a query and I need to check to see if a field is occupied, i.e., it can have anything in it, i just want to see if something is there... this is what I want, but of course, anything isn't the right word here...
and (r.id = 'anything')
View 7 Replies
View Related