How To Simplify My Endless Query. Thanks.
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 months
since they opened their accounts. The tricky part here is accounts
starting with '28' are treated differently than other accounts, they
are given 3 months grace period. In other words, for all other
accounts, their month0 balance is the balance of their open_month, and
month1 balance is the balance after the account is opened 1 month, and
so on. But accounts starting with '28' month0 balance would be the
balance after the account is opened 3 months, and month1 balance would
be the balance after the account is opened 4 months, and so on.
My query below works, but since some customers are more than 10 years
old (more than 120 months), my query is endless! Does anyone know a
better 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_balance
120000017008009001000
2280000110000150002000030000
select a.person_id
,a.account
,month0_balance=case
when a.account like '2%' and a.account not like '28%'
then
sum(case datediff(mm, a.open_date, balance_date) when 0
then 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 =case
when a.account like '2%' and a.account not like '28%'
then
sum(case datediff(mm, a.open_date, balance_date) when 1
then b.balance else 0 end)
else sum(case datediff(mm, a.open_date, balance_date)
when 4 then b.balance else 0 end)
end
from a as a
join b as b
on a.account=b.account
group by a.person_id, a.account
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
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
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
Apr 11, 2015
I created a function to use in a View, works similar to DATEADD but only with my company's Business days Monday-Thursday.
I am running a query but it never ends to run.
This is the function:
USE [RA_dev]
GO
/****** Object: UserDefinedFunction [Production].[GBDATEADD] Script Date: 4/11/2015 5:58:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
[Code] ...
This is how I am trying to use it in the View:
Production.GBDATEADD(Production.Schedule.START_DATE, Production.Operations_Data_Pool.MFG_DAY - 1) AS SCH_DATE
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
May 14, 2004
*** edited by: master4eva ***
Please enclose your code in </ code> tags (without the space between the "</" and "code"). This will make your code easier to read online; therefore, encouraging a response to be faster. It is to your own benefit for your question to be answered in future.
I have already done the editing to include the <code></ code> tags.
*********
I have a trigger that fires this stored procedure during an update event. But i think i am getting an endless loop. Any idea? Thanks in advance....
<code>
ALTER PROCEDURE TrigRetReqRecIDP1
@REID int
AS
Declare @RRID int
Declare @intREID varchar(20)
Declare @intIMID varchar(20)
Declare @RetValint
Declare cr cursor
for
select RRID from RequestRecords where REID=@REID and RRStatus = 'PE'
open cr
fetch next from cr
into
@RRID
while @@fetch_status = 0
Begin
select @intIMID = (select IMID from ImplementationGroup where ImGrpName = 'Help Desk')
insert into ImplementationTasks
(
IMID,
ITStatus,
ITStatusDate
)
VALUES
(
@intIMID,
'2',
GetDate()
)
SET @RetVal = @@IDENTITY
Update RequestRecords
set ITID = @RETVal, RRStatus = 'IA'
where REID = @REID and RRID = @RRID
end
close cr
deallocate cr
GO
View 6 Replies
View Related
Feb 17, 2000
I have an SQL script that runs as part of a batch process in order to number line items in timecards. It basically consists of 2 nested cursors with a number increment and update inside the inner cursor. The problem is that it gets stuck (seemingly at random) in a loop (incrementing and updating within the inner cursor) until I get an arithmetic overflow and it just moves on to the next card. I'm new to my job as a dba and the boss is breathing down my neck.....any assistance would be GREATLY appreciated!!
Thanks..Nick
Here is the code for the script:
declare @SEQ int,
@NUM smallint,
@SUM smallint,
@TSQ int,
@TLI int
declare LINES_OUT_OF_SEQ_CSR cursor for
select TIMECARD_SEQ_NBR
from EMPL_TMCD_VER_DETL
where NEW = '1'
order by TIMECARD_SEQ_NBR
open LINES_OUT_OF_SEQ_CSR
fetch next from LINES_OUT_OF_SEQ_CSR into @SEQ
while @@fetch_status = 0
begin
declare LINES_TO_CHG_SEQ_CSR cursor for
select TIMECARD_SEQ_NBR,
LINE_ITEM_SEQ_NBR
from EMPL_TMCD_VER_DETL
where TIMECARD_SEQ_NBR = @SEQ
order by LINE_ITEM_SEQ_NBR
select @NUM = 0
open LINES_TO_CHG_SEQ_CSR
fetch next from LINES_TO_CHG_SEQ_CSR into @TSQ, @TLI
while @@fetch_status = 0
begin
select @SUM = @NUM +1
select @NUM = @SUM
update EMPL_TMCD_VER_DETL
set TIMECARD_VERSION_ITEM_NBR = @NUM
where LINE_ITEM_SEQ_NBR = @TLI
and TIMECARD_SEQ_NBR = @TSQ
fetch next from LINES_TO_CHG_SEQ_CSR into @TSQ, @TLI
end
deallocate LINES_TO_CHG_SEQ_CSR
fetch next from LINES_OUT_OF_SEQ_CSR into @SEQ
end
deallocate LINES_OUT_OF_SEQ_CSR
go
View 2 Replies
View Related
Jan 29, 2004
i have created a job that i have scheduled to run every 10 min everything is configured well since i have tested preety everything their is to be tested and found that it was my last step wich as a fetch in it so i imagine that this fetch is making it loop over and over again. the job goes trought all the steps and starts back at the first step and keep going like that till i disable it here is my fetch statement and if you have any clue any help would be widely apreciated.
PS: i suspected it to be that fetch statement causing the havoc ;)
DECLARE
@TransactionNb varchar(10),
@EqId varchar(10)
DECLARE TransactionNb_cursor CURSOR
FOR
SELECT TransactionNb, EqId
FROM DetCom
WHERE UpdCode = 'C'
OPEN TransactionNb_cursor
FETCH NEXT FROM TransactionNb_cursor
INTO @TransactionNb, @EqId
WHILE @@FETCH_STATUS <> -1
BEGIN
-- Vérifier s'il existe une transaction avec le UpdCode = 'C' dans EntCom
IF (SELECT UpdCode
FROM EntCom
WHERE TransactionNb = @TransactionNb and EqId = @EqId) = 'C'
BEGIN
CONTINUE
END
ELSE
BEGIN
RAISERROR (50006, 10, 0, @TransactionNb, @EqId)
END
FETCH NEXT FROM TransactionNb_cursor
INTO @TransactionNb, @EqId
END
CLOSE TransactionNb_cursor
DEALLOCATE TransactionNb_cursor
View 1 Replies
View Related
Aug 16, 2007
I have a table with two columns: OID and Cumulative (witch is the same type as OID)
Each OID can have one or more Cumulatives.
Example of data:
OID Cumulative
167 292
167 294
167 296
168 292
169 302
169 304
The cumulation of each OID don't stop at one cumulation, but can be endless (theoretical).
Example: 167->292->590
So the table would have on more row:
OID Cumulative
295 505
I would like to represent this strucuture in a tree view and I'm looking for a query that could give me a table with this structure:
OID Cumul1 Cumul2 Cuml3 Cuml4 .... Cumuln
in the way I can read the row and have as many child nodes as I have values in the columns. The number of columns depends on the row with most cumulations.
How can I do the query?
Is there a better way as my table with n columns?
Thanks for suggestions
View 1 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
Feb 28, 2007
I'm having a problem where I'm using a Execute SQL Task to retrieve a dataset and storing that in an object variable. Then on success of that execute sql task I use a foreach loop task to go through the dataset and do 2 tasks inside the foreach loop. When I execute this package I have ~12 records in the dataset however when I get to the foreach loop in the 2nd iteration it keeps repeating it. It acts like it is stuck on the second record (tuple) and never goes on. I'm using an ForEach ADO Enumerator in the foreach. I've even set a breakpoint on each iteration and no task fails in side the foreach loop. I'm completely perplexed why it will iterate to the 2nd record but get stuck there in an endless loop. I've tried this on 2 different computers (with different data values) and the same thing happens. Does anyone have any suggestions?
View 40 Replies
View Related
Jan 15, 2007
I have a package which runs fine, when I execute it with my account (e.g. double-click on the .dtsx file and run it).
Now I would like to establish a job, which starts the package. I created first a credential for my Account (which is a domain administrator account also for the box, where SQL Server is running on), then I defined a proxy to this credential.
In the job definition I changed the Run as... to this Proxy (it is a SSIS Proxy) and then I started the job.
Th job does NOT abend, it runs forever! So I have to stop it manually.
In the log I can see as last entry : "operation complete". It stops at a "Execute process task" where I call the bcp utility.
Does anyone has an idea, why a package can run forever?!?!
Regards
Norbert
View 1 Replies
View Related
Dec 19, 2003
I'm running a query, actually its an insert that works when using the TSQL below.
However when I try to use the debugger to step through and using the exact same values as those below I get the following error:
[Microsoft][ODBC SQL Server Driver]Invalid character value for cast specification
Its Killing me because everything else works, but this. Can somebody help.
DECLARE @NoteID INT,-- NULL OUTPUT,
@Note_Description NVARCHAR(3000),-- = NULL,
@Date DateTime,-- = NULL OUTPUT,
@ByWho NVARCHAR(30),-- = NULL,
@FK_Action_Performed NVARCHAR(40),-- = NULL,
@FK_UserID INT,-- = NULL,
@FK_JobID INT,-- = NULL,
@Job_Date DateTime,-- = NULL,
@Start DateTime,-- = NULL,
@Finish DateTime,-- = NULL,
@BeenRead NVARCHAR(10),-- = NULL
@FK_UserIDList NVARCHAR(4000)-- = NULL
--SET @NoteID = 409 --NULL OUTPUT,
SET @Note_Description = 'Tetsing'
--SET @Date DateTime = NULL OUTPUT,
SET @ByWho = 'GeorgeAgaian'
SET @FK_Action_Performed = 'Worked hard'
SET @FK_UserID = 5
SET @FK_JobID = 29
SET @Job_Date = 28/01/03
SET @Start = '1:00:20 PM'
SET @Finish = '1:00:20 PM'
SET @BeenRead = 'UnRead'
SET @FK_UserIDList = '1,2,3'
--AS
--SET NOCOUNT ON
SET NOCOUNT ON
SET XACT_ABORT ON
BEGIN TRANSACTION
SET @Date = GETDATE()
-- Insert Values into the customer table
INSERT Note (Note_Description,
Date,
ByWho,
FK_Action_Performed,
FK_UserID,
FK_JobID,
Job_Date,
Start,
Finish)
SELECT --@NoteID,
@Note_Description,
@Date,
@ByWho,
@FK_Action_Performed,
@FK_UserID,
@FK_JobID,
@Job_Date,
@Start,
@Finish
-- Get the new Customer Identifier, return as OUTPUT param
SELECT @NoteID = @@IDENTITY
-- Insert new notes for all the users that the note pertains to, in this case this will be by the assigned
-- users.
IF @FK_UserIDList IS NOT NULL
EXECUTE spInsertNotesByAssignedUsers @NoteID, @FK_UserIDList
-- Insert New Address record
-- Retrieve Address reference into @AddressId
-- EXEC spInsertForUserNote
-- @FK_UserID,
--@NoteID,
-- @BeenRead
-- @Fax,
-- @PKId,
-- @AddressId OUTPUT
COMMIT TRANSACTION
--------------------------------------------------
GO
View 1 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
Jan 22, 2001
Hi,
I get this error dialog when I try to open all the rows of any table from Enterprise manager..
Any help would be really appreciated..
Thanks,
-Srini.
View 1 Replies
View Related
May 24, 2007
SQL Server 2005 9.0.3161 on Win 2k3 R2
I receive the following error:
"Error: 8624, Severity: 16, State: 1 Internal Query Processor Error: The query processor could not produce a query plan. For more information, contact Customer Support Services."
I have traced this to an insert statement that executes as part of a stored procedure.
INSERT INTO ledger (journal__id, account__id,account_recv_info__id,amount)
VALUES (@journal_id, @acct_id, @acct_recv_id, @amount)
There is also an auto-increment column called id. There are FK contraints on all of the columns ending in "__id". I have found that if I remove the contraint on account__id the procedure will execute without error. None of the other constraints seem to make a difference. Of course I don't want to remove this key because it is important to the database integrity and should not be causing problems, but apparently it confuses the optimizer.
Also, the strange thing is that I can get the procedure to execute without error when I run it directly through management studio, but I receive the error when executing from .NET code or anything using ODBC (Access).
View 5 Replies
View Related
Mar 28, 2007
Hey, i've written a query to search a database dependant on variables chosen by user etc etc. Opened up a new sqldatasource, entered the query shown below and went on to the test query page. Entered some test variables, everything works as it should do. Try to get it to show in a datagrid on a webpage - nothing. No data shows.
SELECT dbo.DERIVATIVES.DERIVATIVE_ID, count(*) AS Matches
FROM dbo.MAKES INNER JOIN
dbo.MODELS ON dbo.MAKES.MAKE_ID = dbo.MODELS.MAKE_ID INNER JOIN
dbo.DERIVATIVES ON dbo.MODELS.MODEL_ID = dbo.DERIVATIVES.MODEL_ID INNER JOIN
dbo.[VALUES] ON dbo.DERIVATIVES.DERIVATIVE_ID = dbo.[VALUES].DERIVATIVE_ID INNER JOIN
dbo.ATTRIBUTES ON dbo.[VALUES].ATTRIBUTE_ID = dbo.ATTRIBUTES.ATTRIBUTE_ID
WHERE ((ATTRIBUTES.ATTRIBUTE_ID = @ATT_ID1 and (@VAL1 is null or VALUE = @VAL1)) or
(ATTRIBUTES.ATTRIBUTE_ID = @ATT_ID2 and (@VAL2 is null or VALUE = @VAL2)) or
(ATTRIBUTES.ATTRIBUTE_ID = @ATT_ID3 and (@VAL3 is null or VALUE = @VAL3)) or
(ATTRIBUTES.ATTRIBUTE_ID = @ATT_ID4 and (@VAL4 is null or VALUE = @VAL4)) )
GROUP BY dbo.DERIVATIVES.DERIVATIVE_ID
HAVING count(*) >= CASE WHEN @VAL1 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN @VAL2 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN @VAL3 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN @VAL4 IS NOT NULL THEN 1 ELSE 0 END -2
ORDER BY count(*) DESC
Here is the page source
<%@ Page Language="VB" MasterPageFile="~/MasterPage.master" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DevConnectionString1 %>"
SelectCommand="	SELECT dbo.DERIVATIVES.DERIVATIVE_ID, count(*) AS Matches 	FROM dbo.MAKES INNER JOIN 				 dbo.MODELS ON dbo.MAKES.MAKE_ID = dbo.MODELS.MAKE_ID INNER JOIN 				 dbo.DERIVATIVES ON dbo.MODELS.MODEL_ID = dbo.DERIVATIVES.MODEL_ID INNER JOIN 				 dbo.[VALUES] ON dbo.DERIVATIVES.DERIVATIVE_ID = dbo.[VALUES].DERIVATIVE_ID INNER JOIN 				 dbo.ATTRIBUTES ON dbo.[VALUES].ATTRIBUTE_ID = dbo.ATTRIBUTES.ATTRIBUTE_ID 	WHERE ((ATTRIBUTES.ATTRIBUTE_ID = @ATT_ID1 and (@VAL1 is null or VALUE = @VAL1)) or 		 (ATTRIBUTES.ATTRIBUTE_ID = @ATT_ID2 and (@VAL2 is null or VALUE = @VAL2)) or 		 (ATTRIBUTES.ATTRIBUTE_ID = @ATT_ID3 and (@VAL3 is null or VALUE = @VAL3)) or 		 (ATTRIBUTES.ATTRIBUTE_ID = @ATT_ID4 and (@VAL4 is null or VALUE = @VAL4)) ) 	GROUP BY dbo.DERIVATIVES.DERIVATIVE_ID 	HAVING count(*) >= CASE WHEN @VAL1 IS NOT NULL THEN 1 ELSE 0 END + 									 CASE WHEN @VAL2 IS NOT NULL THEN 1 ELSE 0 END + 									 CASE WHEN @VAL3 IS NOT NULL THEN 1 ELSE 0 END + 									 CASE WHEN @VAL4 IS NOT NULL THEN 1 ELSE 0 END -2 	ORDER BY count(*) DESC ">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="ATT_ID1" PropertyName="SelectedValue" />
<asp:ControlParameter ControlID="TextBox1" Name="VAL1" PropertyName="Text" />
<asp:Parameter Name="ATT_ID2" />
<asp:Parameter Name="VAL2" />
<asp:Parameter Name="ATT_ID3" />
<asp:Parameter Name="VAL3" />
<asp:Parameter Name="ATT_ID4" />
<asp:Parameter Name="VAL4" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:DevConnectionString1 %>"
SelectCommand="SELECT * FROM [ATTRIBUTES]"></asp:SqlDataSource>
<br />
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2"
DataTextField="ATTRIBUTE_NAME" DataValueField="ATTRIBUTE_ID">
</asp:DropDownList>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"></asp:TextBox><br />
<br />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="DERIVATIVE_ID"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="DERIVATIVE_ID" HeaderText="DERIVATIVE_ID" InsertVisible="False"
ReadOnly="True" SortExpression="DERIVATIVE_ID" />
<asp:BoundField DataField="Matches" HeaderText="Matches" ReadOnly="True" SortExpression="Matches" />
</Columns>
</asp:GridView>
</asp:Content>
AFAIK I have configured the source to pick up the dropdownlist value and the textbox value (the text box is autopostback).
Am i not submitting the data correctly? (It worked with a simple query...just not with this one). I have tried a stored procedure which works when testing just not when its live on a webpage.
Please help!
(Visual Web Devleoper 2005 Express and SQL Server Management Studio Express)
View 4 Replies
View Related
Aug 5, 2014
I have the following code.
SELECT _bvSerialMasterFull.SerialNumber, _bvSerialMasterFull.SNStockLink, _bvSerialMasterFull.SNDateLMove, _bvSerialMasterFull.CurrentLoc,
_bvSerialMasterFull.CurrentAccLink, _bvSerialMasterFull.StockCode, _bvSerialMasterFull.CurrentAccount, _bvSerialMasterFull.CurrentLocationDesc,
_bvSerialNumbersFull.SNTxDate, _bvSerialNumbersFull.SNTxReference, _bvSerialNumbersFull.SNTrCodeID, _bvSerialNumbersFull.SNTransType,
_bvSerialNumbersFull.SNWarehouseID, _bvSerialNumbersFull.TransAccount, _bvSerialNumbersFull.TransTypeDesc,
[code]...
However, as you can see, the original select query is run twice and joined together.What I was hoping for is this to be done in the original query without the need to duplicate the original query.
View 2 Replies
View Related
Jun 15, 2007
I'm trying to find the command to open up an odbc conection inside sql2005 express. I only have ues of an odbc connector, we're conection to remedy. We will eventually be using stored procedures to extract the data we need from remedy and doing additional data crunching. I'm a foxpro programmer so once I get the correct syntax for making the odbc connector I shold be ok. Also I need a really good advanced book on sql2005. The type of book that would have my odbc answer. I've spent all morning trying to find this information and was unable to.
Thanks in advance
Daniel Buchanan.
If this was the wrong forum to post this on, please move this question to the correct one. I need this answer soon.
View 1 Replies
View Related
Jul 19, 2015
We have a issue with a MDS server that have been over us for a couple of days, the original error msg from SQL Server Engine is the one "The query processor could not produce a query plan" but the ones we get on the Excel-Addin are "Sequece contains no elements" or "The value cannot be null" T
• Using Microsoft SQL Server 2012 (SP1) - 11.0.3393.0 (X64) for 6months on this server without issues
• Two weeks ago we started to have 2 errors: "Sequence Contains No Elements" | "The Value Cannot Be Null"
• We are using the last version of Excel Add-in
• We try to reinstall the MDS feature
• If I backup/restore MDS database to other server it works
• We updated to SQL 2012 SP2 + CU4 but the error persisted ...
Looking at the MDSTraceLog we are routed to the this msg
SQL Error Debug Info: Number: 8624, Message: Internal Query Processor Error: The query processor could not produce a query plan. For more information, contact Customer Support Services., Server: bbdvsql03inst01, Proc: udpMetadataEntityGetDetailsXML, Line: 28
At line 28 udpMetadataEntityGetDetailsXML is calling udfMetadataEntityGetDetailsXML … and here is where we stopped
** Error found when try to get data from a entity using Excel add-in **
===================================
Sequence contains no elements
------------------------------
Program Location:
  at Microsoft.MasterDataServices.AsyncEssentials.AsyncResultBase.EndInvoke()
  at Microsoft.MasterDataServices.ExcelAddInCore.AsyncProviderBase`1.EndOperation(IAsyncResult ar)
[code]....
View 3 Replies
View Related
Jun 26, 2015
how do I get the variables in the cursor, set statement, to NOT update the temp table with the value of the variable ? I want it to pull a date, not the column name stored in the variable...
create table #temptable (columname varchar(150), columnheader varchar(150), earliestdate varchar(120), mostrecentdate varchar(120))
insert into #temptable
SELECT ColumnName, headername, '', '' FROM eddsdbo.[ArtifactViewField] WHERE ItemListType = 'DateTime' AND ArtifactTypeID = 10
--column name
declare @cname varchar(30)
[code]...
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
Apr 30, 2007
Hello everybody,
I'm developing a report using the following structure :
declare @sql as nvarchar(4000)
declare @where as nvarchar(2000)
set @sql = 'select ....'
If <conditional1>
begin
set @where = 'some where'
end
If <conditional2>
begin
set @where = 'some where'
end
set @sql = @sql + @where
exec(@sql)
I run it in query analyser and works fine, but when I try to run in Reporting Services, Visual studio stops responding and the cpu reaches 100 %.
I realize that when I cut off the if clauses, then it works at Reporting services.
Does anybody know what is happening?
Why the query works in query analyser and doesn't work in Reporting Service ?
Thanks,
MaurÃcio
View 2 Replies
View Related
Oct 6, 2015
SQL Server 2012 Performance Dashboard Main advices me this:
Since the application is from a vendor and I have no control over its code, how can improve this sitation?
View 3 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
Nov 15, 2007
do i need to nest a query in RS if i want a calculated column to be compared against a multi value variable? It looks like coding WHERE calcd name in (@variable) violates SQL syntax. My select looked like
SELECT ... ,CASE enddate WHEN null then 1 else 0 END calcd name
FROM...
WHERE ... and calcd name in (@variable)
View 1 Replies
View Related
Oct 30, 2015
When viewing an estimated query plan for a stored procedure with multiple query statements, two things stand out to me and I wanted to get confirmation if I'm correct.
1. Under <ParameterList><ColumnReference... does the xml attribute "ParameterCompiledValue" represent the value used when the query plan was generated?
<ParameterList>
<ColumnReference Column="@Measure" ParameterCompiledValue="'all'" />
</ParameterList>
</QueryPlan>
</StmtSimple>
2. Does each query statement that makes up the execution plan for the stored procedure have it's own execution plan? And meaning the stored procedure is made up of multiple query plans that could have been generated at a different time to another part of that stored procedure?
View 0 Replies
View Related
Mar 25, 2008
Hi all,
In the Programmability/Stored Procedure of Northwind Database in my SQL Server Management Studio Express (SSMSE), I have the following sql:
USE [Northwind]
GO
/****** Object: StoredProcedure [dbo].[SalesByCategory] Script Date: 03/25/2008 08:31:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SalesByCategory]
@CategoryName nvarchar(15), @OrdYear nvarchar(4) = '1998'
AS
IF @OrdYear != '1996' AND @OrdYear != '1997' AND @OrdYear != '1998'
BEGIN
SELECT @OrdYear = '1998'
END
SELECT ProductName,
TotalPurchase=ROUND(SUM(CONVERT(decimal(14,2), OD.Quantity * (1-OD.Discount) * OD.UnitPrice)), 0)
FROM [Order Details] OD, Orders O, Products P, Categories C
WHERE OD.OrderID = O.OrderID
AND OD.ProductID = P.ProductID
AND P.CategoryID = C.CategoryID
AND C.CategoryName = @CategoryName
AND SUBSTRING(CONVERT(nvarchar(22), O.OrderDate, 111), 1, 4) = @OrdYear
GROUP BY ProductName
ORDER BY ProductName
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
From an ADO.NET 2.0 book, I copied the code of ConnectionPoolingForm to my VB 2005 Express. The following is part of the code:
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.Common
Imports System.Diagnostics
Public Class ConnectionPoolingForm
Dim _ProviderFactory As DbProviderFactory = SqlClientFactory.Instance
Public Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
'Force app to be available for SqlClient perf counting
Using cn As New SqlConnection()
End Using
InitializeMinSize()
InitializePerfCounters()
End Sub
Sub InitializeMinSize()
Me.MinimumSize = Me.Size
End Sub
Dim _SelectedConnection As DbConnection = Nothing
Sub lstConnections_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lstConnections.SelectedIndexChanged
_SelectedConnection = DirectCast(lstConnections.SelectedItem, DbConnection)
EnableOrDisableButtons(_SelectedConnection)
End Sub
Sub DisableAllButtons()
btnAdd.Enabled = False
btnOpen.Enabled = False
btnQuery.Enabled = False
btnClose.Enabled = False
btnRemove.Enabled = False
btnClearPool.Enabled = False
btnClearAllPools.Enabled = False
End Sub
Sub EnableOrDisableButtons(ByVal cn As DbConnection)
btnAdd.Enabled = True
If cn Is Nothing Then
btnOpen.Enabled = False
btnQuery.Enabled = False
btnClose.Enabled = False
btnRemove.Enabled = False
btnClearPool.Enabled = False
Else
Dim connectionState As ConnectionState = cn.State
btnOpen.Enabled = (connectionState = connectionState.Closed)
btnQuery.Enabled = (connectionState = connectionState.Open)
btnClose.Enabled = btnQuery.Enabled
btnRemove.Enabled = True
If Not (TryCast(cn, SqlConnection) Is Nothing) Then
btnClearPool.Enabled = True
End If
End If
btnClearAllPools.Enabled = True
End Sub
Sub StartWaitUI()
Me.Cursor = Cursors.WaitCursor
DisableAllButtons()
End Sub
Sub EndWaitUI()
Me.Cursor = Cursors.Default
EnableOrDisableButtons(_SelectedConnection)
End Sub
Sub SetStatus(ByVal NewStatus As String)
RefreshPerfCounters()
Me.statusStrip.Items(0).Text = NewStatus
End Sub
Sub btnConnectionString_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnConnectionString.Click
Dim strConn As String = txtConnectionString.Text
Dim bldr As DbConnectionStringBuilder = _ProviderFactory.CreateConnectionStringBuilder()
Try
bldr.ConnectionString = strConn
Catch ex As Exception
MessageBox.Show(ex.Message, "Invalid connection string for " + bldr.GetType().Name, MessageBoxButtons.OK, MessageBoxIcon.Error)
Return
End Try
Dim dlg As New ConnectionStringBuilderDialog()
If dlg.EditConnectionString(_ProviderFactory, bldr) = System.Windows.Forms.DialogResult.OK Then
txtConnectionString.Text = dlg.ConnectionString
SetStatus("Ready")
Else
SetStatus("Operation cancelled")
End If
End Sub
Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAdd.Click
Dim blnError As Boolean = False
Dim strErrorMessage As String = ""
Dim strErrorCaption As String = "Connection attempt failed"
StartWaitUI()
Try
Dim cn As DbConnection = _ProviderFactory.CreateConnection()
cn.ConnectionString = txtConnectionString.Text
cn.Open()
lstConnections.SelectedIndex = lstConnections.Items.Add(cn)
Catch ex As Exception
blnError = True
strErrorMessage = ex.Message
End Try
EndWaitUI()
If blnError Then
SetStatus(strErrorCaption)
MessageBox.Show(strErrorMessage, strErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
SetStatus("Connection opened succesfully")
End If
End Sub
Sub btnOpen_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnOpen.Click
StartWaitUI()
Try
_SelectedConnection.Open()
EnableOrDisableButtons(_SelectedConnection)
SetStatus("Connection opened succesfully")
EndWaitUI()
Catch ex As Exception
EndWaitUI()
Dim strErrorCaption As String = "Connection attempt failed"
SetStatus(strErrorCaption)
MessageBox.Show(ex.Message, strErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Sub btnQuery_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnQuery.Click
Dim queryDialog As New QueryDialog()
If queryDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Me.Cursor = Cursors.WaitCursor
DisableAllButtons()
Try
Dim cmd As DbCommand = _SelectedConnection.CreateCommand()
cmd.CommandText = queryDialog.txtQuery.Text
Using rdr As DbDataReader = cmd.ExecuteReader()
If rdr.HasRows Then
Dim resultsForm As New QueryResultsForm()
resultsForm.ShowResults(cmd.CommandText, rdr)
SetStatus(String.Format("Query returned {0} row(s)", resultsForm.RowsReturned))
Else
SetStatus(String.Format("Query affected {0} row(s)", rdr.RecordsAffected))
End If
Me.Cursor = Cursors.Default
EnableOrDisableButtons(_SelectedConnection)
End Using
Catch ex As Exception
Me.Cursor = Cursors.Default
EnableOrDisableButtons(_SelectedConnection)
Dim strErrorCaption As String = "Query attempt failed"
SetStatus(strErrorCaption)
MessageBox.Show(ex.Message, strErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Else
SetStatus("Operation cancelled")
End If
End Sub
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
I executed the code successfully and I got a box which asked for "Enter the query string".
I typed in the following: EXEC dbo.SalesByCategory @Seafood. I got the following box: Query attempt failed. Must declare the scalar variable "@Seafood". I am learning how to enter the string for the "SQL query programed in the subQuery_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnQuery.Click" (see the code statements listed above). Please help and tell me what I missed and what I should put into the query string to get the information of the "Seafood" category out.
Thanks in advance,
Scott Chang
View 4 Replies
View Related
Nov 7, 2007
I have two tables .. in one (containing user data, lets call it u).The important fields are:u.userName, u.userID (uniqueidentifier) and u.workgroupID (uniqueidentifier)The second table (w) has fieldsw.delegateID (uniqueidentifier), w.workgroupID (uniqueidentifier) The SP takes the delegateID and I want to gather all the people from table u where any of the workgroupID's for that delegate match in w. one delegateID may be tied to multiple workgroupID's. I know I can create a temporary table (@wgs) and do a: INSERT INTO @wgs SELECT workgroupID from w WHERE delegateID = @delegateIDthat creates a result set with all the workgroupID's .. this may be one, none or multipleI then want to get all u.userName, u.userID FROM u WHERE u.workgroupIDThis query works on an individual workgroupID (using another temp table, @users to aggregate the results was my thought, so that's included) INSERT INTO @users SELECT u.userName,u.userID FROM tableU u LEFT JOIN tableW w ON w.workgroupID = u.workgroupID WHERE u.workgroupID = @workGroupIDI'm trying to avoid looping or using a CURSOR for the performance hit (had to kick the development server after one of the cursor attempts yesterday)Essentially what I'm after is: SELECT u.userName,u.userID
FROM tableU u
LEFT JOIN tableW w ON w.workgroupID = u.workgroupID
WHERE u.workgroupID = (SELECT workgroupID from w WHERE delegateID = @delegateID) ... but that syntax does not work and I haven't found another work around yet.TIA!
View 1 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
Jan 7, 2002
I am trying to run queries against any of the user tables in my MS SQL 7.0 database. I get a message the Query Designer encountered a query error.
We have tried rebooting the SQL Server and I am still getting these messages. Also, the SQL error logs look fine - all database
maintenance are running successfully including the DBCCs which show no errors. Any help would be greatly appreciated as we are to go
into production in a few days.
View 2 Replies
View Related