I have a stored procedure such as below :
CREATE PROCEDURE [dbo].[sp_InsertPumpsStatus] (
#Frequency1 FLOAT,
#Power1 FLOAT,
#Db1 FLOAT,
#Efficiency1 FLOAT,
#Frequency2 FLOAT,
#Power2 FLOAT,
#Db2 FLOAT,
#Efficiency2 FLOAT,
#Frequency3 FLOAT = NULL,
#Power3 FLOAT = NULL,
#Db3 FLOAT = NULL,
#Efficiency3 FLOAT = NULL,
#Frequency4 FLOAT = NULL,
#Power4 FLOAT = NULL,
#Db4 FLOAT = NULL,
#Efficiency4 FLOAT = NULL,
#Frequency5 FLOAT = NULL,
#Power5 FLOAT = NULL,
#Db5 FLOAT = NULL,
#Efficiency5 FLOAT = NULL,
#Frequency6 FLOAT = NULL,
#Power6 FLOAT = NULL,
#Db6 FLOAT = NULL,
#Efficiency6 FLOAT = NULL,
#Frequency7 FLOAT = NULL,
#Power7 FLOAT = NULL,
#Db7 FLOAT = NULL,
#Efficiency7 FLOAT = NULL,
#Frequency8 FLOAT = NULL,
#Power8 FLOAT = NULL,
#Db8 FLOAT = NULL,
#Efficiency8 FLOAT = NULL,
#Frequency9 FLOAT = NULL,
#Power9 FLOAT = NULL,
#Db9 FLOAT = NULL,
#Efficiency9 FLOAT = NULL,
#Frequency10 FLOAT = NULL,
#Power10 FLOAT = NULL,
#Db10 FLOAT = NULL,
#Efficiency10 FLOAT = NULL,
#SolarDateTime NVARCHAR(20),
#Date DATETIME
)
AS
BEGIN
INSERT INTO [dbo].sp_InsertPumpsStatus
(
[Frequency1],
[Power1],
[Db1],
[Efficiency1],
[Frequency2],
[Power2],
[Db2],
[Efficiency2],
[Frequency3],
[Power3],
[Db3],
[Efficiency3],
[Frequency4],
[Power4],
[Db4],
[Efficiency4],
[Frequency5],
[Power5],
[Db5],
[Efficiency5],
[Frequency6],
[Power6],
[Db6],
[Efficiency6],
[Frequency7],
[Power7],
[Db7],
[Efficiency7],
[Frequency8],
[Power8],
[Db8],
[Efficiency8],
[Frequency9],
[Power9],
[Db9],
[Efficiency9],
[Frequency10],
[Power10],
[Db10],
[Efficiency10],
[SolarDateTime],
[Date]
)
VALUES
(
#Frequency1,
#Power1,
#Db1,
#Efficiency1,
#Frequency2,
#Power2,
#Db2,
#Efficiency2,
#Frequency3,
#Power3,
#Db3,
#Efficiency3,
#Frequency4,
#Power4,
#Db4,
#Efficiency4,
#Frequency5,
#Power5,
#Db5,
#Efficiency5,
#Frequency6,
#Power6,
#Db6,
#Efficiency6,
#Frequency7,
#Power7,
#Db7,
#Efficiency7,
#Frequency8,
#Power8,
#Db8,
#Efficiency8,
#Frequency9,
#Power9,
#Db9,
#Efficiency9,
#Frequency10,
#Power10,
#Db10,
#Efficiency10,
#SolarDateTime,
#DATE
)
END
when I execute this procedure, I get an error:
Invalid object name 'dbo.sp_InsertPumpsStatus'
What is problem?
Invalid object name 'dbo.sp_InsertPumpsStatus'.
In your script, It can be clearly seen that, You are giving same name to the stored procedure as the table in statement. Make sure the defined table on Insert statement is correct. If it is correct, Give another name to the stored procedure.
Related
I have the following SQL code below that is returning an error message stating that the AvgPYs column is not valid. This is also impacting my Auth column. Is there an issue with my formula? Any help is appreciated.
SELECT [tblCeiling].[Proj Code], [tblCeiling].[Act Code], [tblCeiling].[Cost Ctr], [tblCeiling].[Date], [tblCeiling].[Ref2], [tblCeiling].[Analyst], [tblCeiling].[Type], [tblCeiling].[B or O], [tblCeiling].[Jul], [tblCeiling].[Aug],
[tblCeiling].[Sep], [tblCeiling].[Oct], [tblCeiling].[Nov], [tblCeiling].[Dec], [tblCeiling].[Jan], [tblCeiling].[Feb], [tblCeiling].[Mar], [tblCeiling].[Apr], [tblCeiling].[May], [tblCeiling].[Jun], [tblCeiling].[Perm], [tblCeiling].[Temp], [tblCeiling].[LimitedTerm],
[tblCeiling].[LTDate], [tblCeiling].[Sal_Rate], [tblCeiling].[New], [Perm] + [Temp] + [LimitedTerm] AS Monthly, Format(([tblCeiling].[Jul] + [tblCeiling].[Aug] + [tblCeiling].[Sep] + [tblCeiling].[Oct] + [tblCeiling].[Nov] + [tblCeiling].[Dec] + [tblCeiling].[Jan] +
[tblCeiling].[Feb] + [tblCeiling].[Mar] + [tblCeiling].[Apr] + [tblCeiling].[May] + [tblCeiling].[Jun]) / 12, '0.0####') AS AvgPYs,
((([Sal_Rate] * [AvgPYs]) * 1000) / 1000) AS Auth, [Dollar Adj] + [Auth] AS Budget, [tblCeiling].[Import], [tblCeiling].[Dollar Adj], [tblCeiling].[OngoingOrOneTime], [tblCeiling].[OneTimeEndingDate]
FROM (SELECT DISTINCT *
FROM [tblactcode]) AS [tblactcode] RIGHT JOIN
(SELECT DISTINCT *
FROM [tblCeiling]) AS [tblCeiling] ON [tblactcode].[Act Code] = [tblCeiling].[Act Code]
WHERE ((([tblCeiling].[Jul]) = iif([jul] IS NULL, 0, [jul])) AND (([tblCeiling].[Aug]) = iif([aug] IS NULL, 0, [aug])) AND (([tblCeiling].[Sep]) = iif([sep] IS NULL, 0, [sep])) AND (([tblCeiling].[Oct]) = iif([oct] IS NULL, 0, [oct])) AND (([tblCeiling].[Nov]) = iif([nov] IS NULL,
0, [nov])) AND (([tblCeiling].[Dec]) = iif([dec] IS NULL, 0, [dec])) AND (([tblCeiling].[Jan]) = iif([jan] IS NULL, 0, [jan])) AND (([tblCeiling].[Feb]) = iif([feb] IS NULL, 0, [feb])) AND (([tblCeiling].[Mar]) = iif([mar] IS NULL, 0, [mar])) AND (([tblCeiling].[Apr])
= iif([apr] IS NULL, 0, [apr])) AND (([tblCeiling].[May]) = iif([may] IS NULL, 0, [may])) AND (([tblCeiling].[Jun]) = iif([jun] IS NULL, 0, [jun])) AND (([tblCeiling].[Import]) = 0))
ORDER BY [tblCeiling].[Proj Code], [tblCeiling].[Cost Ctr], [tblCeiling].[Date]
Here is the specific line I'm referring to:
Format(([tblCeiling].[Jul] + [tblCeiling].[Aug] + [tblCeiling].[Sep] + [tblCeiling].[Oct] + [tblCeiling].[Nov] + [tblCeiling].[Dec] + [tblCeiling].[Jan] +
[tblCeiling].[Feb] + [tblCeiling].[Mar] + [tblCeiling].[Apr] + [tblCeiling].[May] + [tblCeiling].[Jun]) / 12, '0.0####') AS AvgPYs,
The specific issue you have run into is attempting to use a calculation in the same scope you are calculating it - which isn't possible. You can only access a calculated value in an outer query.
Or a neat solution is to use CROSS APPLY which allows you to reuse a calculation as follows. In general this is done as:
select -- existing columns before AvgPYs
, AvgPYs
-- , some formula which depends on AvgPYs
from (
-- existing query
) C -- C is an acceptable short alias for Ceiling
cross apply (
values (formula)
) X (AvgPYs)
In your case I think the following is correct:
SELECT C.[Proj Code], C.[Act Code], C.[Cost Ctr], C.[Date], C.[Ref2], C.[Analyst], C.[Type], C.[B or O], C.[Jul], C.[Aug]
, C.[Sep], C.[Oct], C.[Nov], C.[Dec], C.[Jan], C.[Feb], C.[Mar], C.[Apr], C.[May], C.[Jun], C.[Perm], C.[Temp], C.[LimitedTerm]
, C.[LTDate], C.[Sal_Rate], C.[New], [Perm] + [Temp] + [LimitedTerm] AS Monthly
, X.AvgPYs
, Y.Auth
, [Dollar Adj] + Y.Auth AS Budget, C.[Import], C.[Dollar Adj], C.[OngoingOrOneTime], C.[OneTimeEndingDate]
FROM (
SELECT DISTINCT *
FROM [tblactcode]
) AS AC
RIGHT JOIN (
SELECT DISTINCT *
FROM [tblCeiling]
) AS C ON AC.[Act Code] = C.[Act Code]
CROSS APPLY (
VALUES (Format((C.[Jul] + C.[Aug] + C.[Sep] + C.[Oct] + C.[Nov] + C.[Dec] + C.[Jan] +
C.[Feb] + C.[Mar] + C.[Apr] + C.[May] + C.[Jun]) / 12, '0.0####'))
) AS X (AvgPYs)
CROSS APPLY (
VALUES (((([Sal_Rate] * X.AvgPYs) * 1000) / 1000))
) Y (Auth)
WHERE (((C.[Jul]) = iif([jul] IS NULL, 0, [jul])) AND ((C.[Aug]) = iif([aug] IS NULL, 0, [aug])) AND ((C.[Sep]) = iif([sep] IS NULL, 0, [sep])) AND ((C.[Oct]) = iif([oct] IS NULL, 0, [oct])) AND ((C.[Nov]) = iif([nov] IS NULL,
0, [nov])) AND ((C.[Dec]) = iif([dec] IS NULL, 0, [dec])) AND ((C.[Jan]) = iif([jan] IS NULL, 0, [jan])) AND ((C.[Feb]) = iif([feb] IS NULL, 0, [feb])) AND ((C.[Mar]) = iif([mar] IS NULL, 0, [mar])) AND ((C.[Apr])
= iif([apr] IS NULL, 0, [apr])) AND ((C.[May]) = iif([may] IS NULL, 0, [may])) AND ((C.[Jun]) = iif([jun] IS NULL, 0, [jun])) AND ((C.[Import]) = 0)
)
ORDER BY C.[Proj Code], C.[Cost Ctr], C.[Date];
Note: A key purpose of a table alias is to have a short reference to the table. See how much easier it is to read with shorter aliases.
I can't work out why my value is being ignored.
In my stored procedure it has these two AND statements
AND (#Current IS NULL OR (o.[OrderStatusId] <> 40) AND (o.[OrderStatusId] <> 30) AND ( NOT ((o.[ShippingStatusId] IN (30, 40)) AND (o.[PaymentStatusId] IN (30, 35, 40)))))
AND (#Printed IS NULL OR o.[Printed] = #Printed)
The #Printed value is a bit same as #Current, and is passed through to the stored procedure just the same as #Current
But the printed value doesn't pull results, it's like it's doing nothing although I know the results should vary.
I'm converting a linq query to the stored procedure, so I know the results should differ.
Here is the part of the linq query which is used.
if (current.HasValue && current.Value)
query = query.Where(o => o.OrderStatusId != (int)OrderStatus.Cancelled && o.OrderStatusId != (int)OrderStatus.Complete && !((o.ShippingStatusId == (int)ShippingStatus.Shipped || o.ShippingStatusId == (int)ShippingStatus.Delivered) && o.Printed && (o.PaymentStatusId == (int)PaymentStatus.Paid || o.PaymentStatusId == (int)PaymentStatus.PartiallyRefunded || o.PaymentStatusId == (int)PaymentStatus.Refunded)));
if (printed.HasValue)
query = query.Where(o => printed.Value == o.Printed);
Any ideas
UPDATE:
Looking at the query from linq in vs debugger I can see the following query, but I' no db expert so I'm a little lost looking at this one.
{SELECT
[Project2].[Id] AS [Id],
[Project2].[OrderGuid] AS [OrderGuid],
[Project2].[StoreId] AS [StoreId],
[Project2].[CustomerId] AS [CustomerId],
[Project2].[BillingAddressId] AS [BillingAddressId],
[Project2].[ShippingAddressId] AS [ShippingAddressId],
[Project2].[PickUpInStore] AS [PickUpInStore],
[Project2].[OrderStatusId] AS [OrderStatusId],
[Project2].[ShippingStatusId] AS [ShippingStatusId],
[Project2].[PaymentStatusId] AS [PaymentStatusId],
[Project2].[PaymentMethodSystemName] AS [PaymentMethodSystemName],
[Project2].[CustomerCurrencyCode] AS [CustomerCurrencyCode],
[Project2].[CurrencyRate] AS [CurrencyRate],
[Project2].[CustomerTaxDisplayTypeId] AS [CustomerTaxDisplayTypeId],
[Project2].[VatNumber] AS [VatNumber],
[Project2].[OrderSubtotalInclTax] AS [OrderSubtotalInclTax],
[Project2].[OrderSubtotalExclTax] AS [OrderSubtotalExclTax],
[Project2].[OrderSubTotalDiscountInclTax] AS [OrderSubTotalDiscountInclTax],
[Project2].[OrderSubTotalDiscountExclTax] AS [OrderSubTotalDiscountExclTax],
[Project2].[OrderShippingInclTax] AS [OrderShippingInclTax],
[Project2].[OrderShippingExclTax] AS [OrderShippingExclTax],
[Project2].[PaymentMethodAdditionalFeeInclTax] AS [PaymentMethodAdditionalFeeInclTax],
[Project2].[PaymentMethodAdditionalFeeExclTax] AS [PaymentMethodAdditionalFeeExclTax],
[Project2].[TaxRates] AS [TaxRates],
[Project2].[OrderTax] AS [OrderTax],
[Project2].[OrderDiscount] AS [OrderDiscount],
[Project2].[OrderTotal] AS [OrderTotal],
[Project2].[RefundedAmount] AS [RefundedAmount],
[Project2].[RewardPointsWereAdded] AS [RewardPointsWereAdded],
[Project2].[CheckoutAttributeDescription] AS [CheckoutAttributeDescription],
[Project2].[CheckoutAttributesXml] AS [CheckoutAttributesXml],
[Project2].[CustomerLanguageId] AS [CustomerLanguageId],
[Project2].[AffiliateId] AS [AffiliateId],
[Project2].[CustomerIp] AS [CustomerIp],
[Project2].[AllowStoringCreditCardNumber] AS [AllowStoringCreditCardNumber],
[Project2].[CardType] AS [CardType],
[Project2].[CardName] AS [CardName],
[Project2].[CardNumber] AS [CardNumber],
[Project2].[MaskedCreditCardNumber] AS [MaskedCreditCardNumber],
[Project2].[CardCvv2] AS [CardCvv2],
[Project2].[CardExpirationMonth] AS [CardExpirationMonth],
[Project2].[CardExpirationYear] AS [CardExpirationYear],
[Project2].[AuthorizationTransactionId] AS [AuthorizationTransactionId],
[Project2].[AuthorizationTransactionCode] AS [AuthorizationTransactionCode],
[Project2].[AuthorizationTransactionResult] AS [AuthorizationTransactionResult],
[Project2].[CaptureTransactionId] AS [CaptureTransactionId],
[Project2].[CaptureTransactionResult] AS [CaptureTransactionResult],
[Project2].[SubscriptionTransactionId] AS [SubscriptionTransactionId],
[Project2].[PaidDateUtc] AS [PaidDateUtc],
[Project2].[ShippingMethod] AS [ShippingMethod],
[Project2].[Printed] AS [Printed],
[Project2].[PrintedOnUtc] AS [PrintedOnUtc],
[Project2].[IsSupport] AS [IsSupport],
[Project2].[EditedStatusId] AS [EditedStatusId],
[Project2].[Deleted] AS [Deleted],
[Project2].[Id1] AS [Id1]
FROM ( SELECT
CASE WHEN (([Extent1].[Printed] <> 1) AND (N'Express Delivery' = [Extent1].[ShippingMethod])) THEN N'1' ELSE N'0' END AS [C1],
CASE WHEN ([Extent1].[Printed] <> 1) THEN CASE WHEN (([Extent1].[ShippingMethod] IN (N'Fast Delivery',N'My Point Pickup')) AND ( NOT EXISTS (SELECT
1 AS [C1]
FROM [dbo].[GenericAttribute] AS [Extent3]
WHERE (N'WarehouseOverride' = [Extent3].[Key]) AND (N'Order' = [Extent3].[KeyGroup]) AND ([Extent3].[EntityId] = [Extent1].[Id])
))) THEN N'0' ELSE N'1' END ELSE N'0' END AS [C2],
[Extent1].[Id] AS [Id],
[Extent1].[OrderGuid] AS [OrderGuid],
[Extent1].[StoreId] AS [StoreId],
[Extent1].[CustomerId] AS [CustomerId],
[Extent1].[BillingAddressId] AS [BillingAddressId],
[Extent1].[ShippingAddressId] AS [ShippingAddressId],
[Extent1].[PickUpInStore] AS [PickUpInStore],
[Extent1].[OrderStatusId] AS [OrderStatusId],
[Extent1].[ShippingStatusId] AS [ShippingStatusId],
[Extent1].[PaymentStatusId] AS [PaymentStatusId],
[Extent1].[PaymentMethodSystemName] AS [PaymentMethodSystemName],
[Extent1].[CustomerCurrencyCode] AS [CustomerCurrencyCode],
[Extent1].[CurrencyRate] AS [CurrencyRate],
[Extent1].[CustomerTaxDisplayTypeId] AS [CustomerTaxDisplayTypeId],
[Extent1].[VatNumber] AS [VatNumber],
[Extent1].[OrderSubtotalInclTax] AS [OrderSubtotalInclTax],
[Extent1].[OrderSubtotalExclTax] AS [OrderSubtotalExclTax],
[Extent1].[OrderSubTotalDiscountInclTax] AS [OrderSubTotalDiscountInclTax],
[Extent1].[OrderSubTotalDiscountExclTax] AS [OrderSubTotalDiscountExclTax],
[Extent1].[OrderShippingInclTax] AS [OrderShippingInclTax],
[Extent1].[OrderShippingExclTax] AS [OrderShippingExclTax],
[Extent1].[PaymentMethodAdditionalFeeInclTax] AS [PaymentMethodAdditionalFeeInclTax],
[Extent1].[PaymentMethodAdditionalFeeExclTax] AS [PaymentMethodAdditionalFeeExclTax],
[Extent1].[TaxRates] AS [TaxRates],
[Extent1].[OrderTax] AS [OrderTax],
[Extent1].[OrderDiscount] AS [OrderDiscount],
[Extent1].[OrderTotal] AS [OrderTotal],
[Extent1].[RefundedAmount] AS [RefundedAmount],
[Extent1].[RewardPointsWereAdded] AS [RewardPointsWereAdded],
[Extent1].[CheckoutAttributeDescription] AS [CheckoutAttributeDescription],
[Extent1].[CheckoutAttributesXml] AS [CheckoutAttributesXml],
[Extent1].[CustomerLanguageId] AS [CustomerLanguageId],
[Extent1].[AffiliateId] AS [AffiliateId],
[Extent1].[CustomerIp] AS [CustomerIp],
[Extent1].[AllowStoringCreditCardNumber] AS [AllowStoringCreditCardNumber],
[Extent1].[CardType] AS [CardType],
[Extent1].[CardName] AS [CardName],
[Extent1].[CardNumber] AS [CardNumber],
[Extent1].[MaskedCreditCardNumber] AS [MaskedCreditCardNumber],
[Extent1].[CardCvv2] AS [CardCvv2],
[Extent1].[CardExpirationMonth] AS [CardExpirationMonth],
[Extent1].[CardExpirationYear] AS [CardExpirationYear],
[Extent1].[AuthorizationTransactionId] AS [AuthorizationTransactionId],
[Extent1].[AuthorizationTransactionCode] AS [AuthorizationTransactionCode],
[Extent1].[AuthorizationTransactionResult] AS [AuthorizationTransactionResult],
[Extent1].[CaptureTransactionId] AS [CaptureTransactionId],
[Extent1].[CaptureTransactionResult] AS [CaptureTransactionResult],
[Extent1].[SubscriptionTransactionId] AS [SubscriptionTransactionId],
[Extent1].[PaidDateUtc] AS [PaidDateUtc],
[Extent1].[ShippingMethod] AS [ShippingMethod],
[Extent1].[Printed] AS [Printed],
[Extent1].[PrintedOnUtc] AS [PrintedOnUtc],
[Extent1].[IsSupport] AS [IsSupport],
[Extent1].[EditedStatusId] AS [EditedStatusId],
[Extent1].[Deleted] AS [Deleted],
[Extent2].[Id] AS [Id1]
FROM [dbo].[Order] AS [Extent1]
LEFT OUTER JOIN [dbo].[RewardPointsHistory] AS [Extent2] ON ([Extent2].[UsedWithOrder_Id] IS NOT NULL) AND ([Extent1].[Id] = [Extent2].[UsedWithOrder_Id])
WHERE ([Extent1].[Deleted] <> 1) AND (40 <> [Extent1].[OrderStatusId]) AND (30 <> [Extent1].[OrderStatusId]) AND ( NOT (([Extent1].[ShippingStatusId] IN (30,40)) AND ([Extent1].[Printed] = 1) AND ([Extent1].[PaymentStatusId] IN (30,35,40))))
) AS [Project2]
ORDER BY [Project2].[C1] DESC, [Project2].[Printed] ASC, [Project2].[C2] DESC, [Project2].[CreatedOnUtc] DESC}
Here is my stored procedure for you to look at:
USE [Test]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[OrderLoad]
-- Add the parameters for the stored procedure here
#OrderId int = null,
#CustomerId int = null,
#WarehouseId int = null,
#BillingCountryId int = null,
#PaymentMethodSystemName nvarchar(max) = null,
#OrderStatusId int = null,
#PaymentStatusId int = null,
#ShippingStatusId int = null,
#BillingEmail nvarchar(max) = null,
#BillingFirstName nvarchar(max) = null,
#BillingLastName nvarchar(max) = null,
#PurchasedPreviously bit = null,
#Printed bit = null,
#OrderNotes nvarchar(max) = null,
#ZendeskId nvarchar(max) = null,
#RexCode nvarchar(max) = null,
#Current bit = null,
#Challenge bit = null,
#ShippingMethod nvarchar(max) = null,
#EditedStatus int = null,
#OrderGuid nvarchar(max) = null,
#SupportReason int = null,
#CreatedFromUtc datetime = null,
#CreatedToUtc datetime = null,
#IsSupport bit = null,
#PageIndex int = 0,
#PageSize int = 2147483644,
#TotalRecords int = null OUTPUT
AS
BEGIN
DECLARE
#sql nvarchar(max)
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
create table #TempTotal (RowNum int identity(1,1), id int);
--select all
INSERT INTO #TempTotal ([id])
SELECT o.[Id]
FROM [Test].[dbo].[Order] o with (NOLOCK)
-- Another alternative to bypass left join, which works with pagination
LEFT join [Test].[dbo].[Address] a on a.Id = o.BillingAddressId and (
coalesce(#BillingEmail,'') <> ''
or coalesce(#BillingFirstName,'') <> ''
or coalesce(#BillingLastName,'') <> ''
or coalesce(#BillingCountryId,'') <> ''
)
WHERE
o.[Deleted] = 0
/*AND (#BillingEmail IS null OR a.[Email] LIKE '%' + #BillingEmail + '%')
AND (#BillingFirstName IS null OR a.[FirstName] LIKE '%' + #BillingFirstName + '%')
AND (#BillingLastName IS null OR a.[LastName] LIKE '%' + #BillingLastName + '%')
AND (#BillingCountryId IS null OR a.[CountryId] = #BillingCountryId)
*/
AND (#Printed IS NULL OR o.[Printed] = #Printed)
AND (#Current IS NULL OR (o.[OrderStatusId] <> 40) AND (o.[OrderStatusId] <> 30) AND ( NOT ((o.[ShippingStatusId] IN (30, 40)) /*AND (o.[Printed] = '1')*/ AND (o.[PaymentStatusId] IN (30, 35, 40)))))
AND (#IsSupport IS null OR o.[IsSupport] = #IsSupport)
--paging
DECLARE #PageLowerBound int
SET #PageLowerBound = #PageSize * #PageIndex
-- Return the paged records
select [Id] --note select * can produce unexpected results
,[OrderGuid]
,[RexOrderId]
,[StoreId]
,[CustomerId]
,[BillingAddressId]
,[ShippingAddressId]
,[PickUpInStore]
,[OrderStatusId]
,[ShippingStatusId]
,[PaymentStatusId]
,[PaymentMethodSystemName]
,[CustomerCurrencyCode]
,[CurrencyRate]
,[CustomerTaxDisplayTypeId]
,[VatNumber]
,[OrderSubtotalInclTax]
,[OrderSubtotalExclTax]
,[OrderSubTotalDiscountInclTax]
,[OrderSubTotalDiscountExclTax]
,[OrderShippingInclTax]
,[OrderShippingExclTax]
,[PaymentMethodAdditionalFeeInclTax]
,[PaymentMethodAdditionalFeeExclTax]
,[TaxRates]
,[OrderTax]
,[OrderDiscount]
,[OrderTotal]
,[RefundedAmount]
,[RewardPointsWereAdded]
,[CheckoutAttributeDescription]
,[CheckoutAttributesXml]
,[CustomerLanguageId]
,[AffiliateId]
,[CustomerIp]
,[AllowStoringCreditCardNumber]
,[CardType]
,[CardName]
,[CardNumber]
,[MaskedCreditCardNumber]
,[CardCvv2]
,[CardExpirationMonth]
,[CardExpirationYear]
,[AuthorizationTransactionId]
,[AuthorizationTransactionCode]
,[AuthorizationTransactionResult]
,[CaptureTransactionId]
,[CaptureTransactionResult]
,[SubscriptionTransactionId]
,[PaidDateUtc]
,[ShippingMethod]
,[Printed]
,[Deleted]
,[CreatedOnUtc]
,[EditedStatusId]
,[IsSupport]
,[PrintedOnUtc]
from [Test].[dbo].[Order] ord with (NOLOCK)
where ord.[Id] in (
select id
from #TempTotal tt
)
ORDER BY
(CASE #IsSupport
WHEN 0 THEN ord.[Printed]
END) ASC
, (CASE #IsSupport
WHEN 0 THEN ord.[CreatedOnUtc]
END) DESC
, (CASE #IsSupport
WHEN 1 THEN ord.[CreatedOnUtc]
END) DESC
--ORDER BY ord.[CreatedOnUtc] DESC
OFFSET #PageLowerBound ROWS FETCH NEXT #PageSize ROWS ONLY;
--total records
select #TotalRecords = count(*) from #TempTotal;
DROP TABLE #TempTotal
END
I have a statement I use to add or update a row of data. I'm observing the SQL updating a row when no apparent changes are present. I'm trying to work out why it's insisting on updating the row when the SQL should prevent it.
I'm updating about 1,000 rows this way (one after another) and only 2 rows seem to update when the mask I've created suggests they shouldn't.
Here's the relevant SQL snippet:
...
ELSE IF NOT EXISTS (
SELECT PERMIT_STATUS, PERMIT_LOCATION, PERMIT_COMMODITY, PERMIT_TYPE_CODE, PERMIT_TYPE_DESCRIPTION, PERMIT_ALLOCATION_METHOD, PERMIT_OPERATION_NAME, OWNERS, SHARE_PERCENTAGE, OPERATOR, MINERALS, PERMIT_DURATION_YEARS, PERMIT_DURATION_MONTHS, PERMIT_AREA, PERMIT_AREA_UNIT, PERMIT_OFFSHORE_ONSHORE, PERMIT_STATUS_DATE, PERMIT_MINERAL_GROUP, PERMIT_MP, SUBSEQUENT_TO_PERMIT, PERMIT_COMMENCEMENT_DATE, PERMIT_EXPIRY_DATE, PERMIT_GRANT_DATE, PERMIT_NONEXCLUSIVE_YN, ShapeGeoJson, Removed
FROM MyTable
WHERE PERMIT_NUMBER = #PERMIT_NUMBER
INTERSECT
SELECT #PERMIT_STATUS, #PERMIT_LOCATION, #PERMIT_COMMODITY, #PERMIT_TYPE_CODE, #PERMIT_TYPE_DESCRIPTION, #PERMIT_ALLOCATION_METHOD, #PERMIT_OPERATION_NAME, #OWNERS, #SHARE_PERCENTAGE, #OPERATOR, #MINERALS, #PERMIT_DURATION_YEARS, #PERMIT_DURATION_MONTHS, #PERMIT_AREA, #PERMIT_AREA_UNIT, #PERMIT_OFFSHORE_ONSHORE, #PERMIT_STATUS_DATE, #PERMIT_MINERAL_GROUP, #PERMIT_MP, #SUBSEQUENT_TO_PERMIT, #PERMIT_COMMENCEMENT_DATE, #PERMIT_EXPIRY_DATE, #PERMIT_GRANT_DATE, #PERMIT_NONEXCLUSIVE_YN, #ShapeGeoJson, #Removed
)
BEGIN
UPDATE MyTable
SET PERMIT_STATUS = #PERMIT_STATUS
,PERMIT_LOCATION = #PERMIT_LOCATION
,PERMIT_COMMODITY = #PERMIT_COMMODITY
,PERMIT_TYPE_CODE = #PERMIT_TYPE_CODE
,PERMIT_TYPE_DESCRIPTION = #PERMIT_TYPE_DESCRIPTION
,PERMIT_ALLOCATION_METHOD = #PERMIT_ALLOCATION_METHOD
,PERMIT_OPERATION_NAME = #PERMIT_OPERATION_NAME
,OWNERS = #OWNERS
,SHARE_PERCENTAGE = #SHARE_PERCENTAGE
,OPERATOR = #OPERATOR
,MINERALS = #MINERALS
,PERMIT_DURATION_YEARS = #PERMIT_DURATION_YEARS
,PERMIT_DURATION_MONTHS = #PERMIT_DURATION_MONTHS
,PERMIT_AREA = #PERMIT_AREA
,PERMIT_AREA_UNIT = #PERMIT_AREA_UNIT
,PERMIT_OFFSHORE_ONSHORE = #PERMIT_OFFSHORE_ONSHORE
,PERMIT_STATUS_DATE = #PERMIT_STATUS_DATE
,PERMIT_MINERAL_GROUP = #PERMIT_MINERAL_GROUP
,PERMIT_MP = #PERMIT_MP
,SUBSEQUENT_TO_PERMIT = #SUBSEQUENT_TO_PERMIT
,PERMIT_COMMENCEMENT_DATE = #PERMIT_COMMENCEMENT_DATE
,PERMIT_EXPIRY_DATE = #PERMIT_EXPIRY_DATE
,PERMIT_GRANT_DATE = #PERMIT_GRANT_DATE
,PERMIT_NONEXCLUSIVE_YN = #PERMIT_NONEXCLUSIVE_YN
,ShapeGeoJson = #ShapeGeoJson
,UpdatedUtc = GETUTCDATE()
,Removed = #Removed
,UpdatedMask = (
IIF ( PERMIT_STATUS != #PERMIT_STATUS, 4096, 0 ) +
IIF ( PERMIT_LOCATION != #PERMIT_LOCATION, 256, 0 ) +
IIF ( PERMIT_COMMODITY != #PERMIT_COMMODITY, 512, 0 ) +
IIF ( PERMIT_TYPE_CODE != #PERMIT_TYPE_CODE, 64, 0 ) +
IIF ( PERMIT_TYPE_DESCRIPTION != #PERMIT_TYPE_DESCRIPTION, 128, 0 ) +
IIF ( PERMIT_ALLOCATION_METHOD != #PERMIT_ALLOCATION_METHOD, 1024, 0 ) +
IIF ( PERMIT_OPERATION_NAME != #PERMIT_OPERATION_NAME, 2048, 0 ) +
IIF ( OWNERS != #OWNERS, 1048576, 0 ) +
IIF ( SHARE_PERCENTAGE != #SHARE_PERCENTAGE, 2097152, 0 ) +
IIF ( OPERATOR != #OPERATOR, 4194304, 0 ) +
IIF ( MINERALS != #MINERALS, 8388608, 0 ) +
IIF ( PERMIT_DURATION_YEARS != #PERMIT_DURATION_YEARS, 32768, 0 ) +
IIF ( PERMIT_DURATION_MONTHS != #PERMIT_DURATION_MONTHS, 65536, 0 ) +
IIF ( PERMIT_AREA != #PERMIT_AREA, 67108864, 0 ) +
IIF ( PERMIT_AREA_UNIT != #PERMIT_AREA_UNIT, 134217728, 0 ) +
IIF ( PERMIT_OFFSHORE_ONSHORE != #PERMIT_OFFSHORE_ONSHORE, 262144, 0 ) +
IIF ( PERMIT_STATUS_DATE != #PERMIT_STATUS_DATE, 8192, 0 ) +
IIF ( PERMIT_MINERAL_GROUP != #PERMIT_MINERAL_GROUP, 131072, 0 ) +
IIF ( PERMIT_MP != #PERMIT_MP, 524288, 0 ) +
IIF ( SUBSEQUENT_TO_PERMIT != #SUBSEQUENT_TO_PERMIT, 33554432, 0 ) +
IIF ( PERMIT_COMMENCEMENT_DATE != #PERMIT_COMMENCEMENT_DATE, 16, 0 ) +
IIF ( PERMIT_EXPIRY_DATE != #PERMIT_EXPIRY_DATE, 32, 0 ) +
IIF ( PERMIT_GRANT_DATE != #PERMIT_GRANT_DATE, 8, 0 ) +
IIF ( PERMIT_NONEXCLUSIVE_YN != #PERMIT_NONEXCLUSIVE_YN, 16384, 0 ) +
IIF ( ShapeGeoJson != #ShapeGeoJson, 137438953472, 0 ) +
IIF ( Removed != #Removed, 274877906944, 0 )
)
WHERE PERMIT_NUMBER = #PERMIT_NUMBER;
END
...
I'm using the INTERSECT method at the top to detect a change in any of the columns of row data. This is because it's easier to compare NULL values in columns.
And you can see the UpdatedMask is being updated with a value to indicate which columns have been updated. When the problem occurs, this is being set to 0 (and when working as expected, I see a correct UpdatedMask).
I can't see any typos or obvious logic errors. So I wonder if it might be due to load on SQL Azure somehow from updating so many records one after another with a sizable ShapeGeoJson column?
Here's the table definition in case it's useful:
CREATE TABLE [dbo].[MyTable](
[PERMIT_NUMBER] [varchar](30) NOT NULL,
[PERMIT_STATUS] [varchar](30) NULL,
[PERMIT_LOCATION] [varchar](4000) NULL,
[PERMIT_COMMODITY] [varchar](8) NULL,
[PERMIT_TYPE_CODE] [varchar](4000) NULL,
[PERMIT_TYPE_DESCRIPTION] [varchar](255) NULL,
[PERMIT_ALLOCATION_METHOD] [varchar](4000) NULL,
[PERMIT_OPERATION_NAME] [varchar](4000) NULL,
[OWNERS] [varchar](4000) NULL,
[SHARE_PERCENTAGE] [varchar](4000) NULL,
[OPERATOR] [varchar](220) NULL,
[MINERALS] [varchar](4000) NULL,
[PERMIT_DURATION_YEARS] [varchar](4000) NULL,
[PERMIT_DURATION_MONTHS] [varchar](4000) NULL,
[PERMIT_AREA] [varchar](4000) NULL,
[PERMIT_AREA_UNIT] [varchar](4) NULL,
[PERMIT_OFFSHORE_ONSHORE] [varchar](4000) NULL,
[PERMIT_STATUS_DATE] [date] NULL,
[PERMIT_MINERAL_GROUP] [varchar](4000) NULL,
[PERMIT_MP] [varchar](4000) NULL,
[SUBSEQUENT_TO_PERMIT] [varchar](4000) NULL,
[PERMIT_COMMENCEMENT_DATE] [date] NULL,
[PERMIT_EXPIRY_DATE] [date] NULL,
[PERMIT_GRANT_DATE] [date] NULL,
[PERMIT_NONEXCLUSIVE_YN] [char](1) NULL,
[ShapeGeoJson] [varchar](max) NOT NULL,
[CreatedUtc] [datetime] NOT NULL,
[UpdatedUtc] [datetime] NOT NULL,
[Removed] [bit] NOT NULL,
[UpdatedMask] [bigint] NULL,
CONSTRAINT [PK_MyTable_1] PRIMARY KEY CLUSTERED
(
[PERMIT_NUMBER] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
Any ideas?
The update process runs nightly so I'll keep my eye on the rows that seem to break my rules to see if there's a pattern there. I've seen this a few times now, but neglected to preserve the data for investigating previously.
In your code you have code duplication. You have the INTERSECT/EXISTS part where you check whether something has been updated or not and then you have the code calculating UpdatedMask where the logic gets repeated.
I would suggest to first remove the duplication of logic. Then it will be much easier to find the problem and fix it on one place.
Below code shows you an alternative way of updating the records and only relying on the code to calculate UpdatedMask.
-- We will update MyTable from data in the NewData alias that contains
-- all of the new values and UpdatedMask
UPDATE U
SET U.PERMIT_STATUS = NewData.PERMIT_STATUS
,U.PERMIT_LOCATION = NewData.PERMIT_LOCATION
.... all other columns ....
,U.UpdatedMask = NewData.UpdatedMask
FROM MyTable U
INNER JOIN (
SELECT T.PERMIT_STATUS = #PERMIT_STATUS
,T.PERMIT_LOCATION = #PERMIT_LOCATION
... all other columns ...
,UpdatedMask = (
IIF ( T.PERMIT_STATUS != #PERMIT_STATUS, 4096, 0 ) +
IIF ( T.PERMIT_LOCATION != #PERMIT_LOCATION, 256, 0 ) +
... all other columns ....
)
FROM MyTable T
WHERE T.PERMIT_NUMBER = #PERMIT_NUMBER
-- In the join clause we only take rows that are actually updated
) AS NewData ON NewData.UpdatedMask<>0
WHERE U.PERMIT_NUMBER = #PERMIT_NUMBER;
I managed to drill down to the issue. The logic for calculating the UpdatedMask value does not take into consideration NULL values when comparing.
So the update is valid. It's the calculated UpdatedMask that's invalid.
So now I've uglified my SQL even further:
UpdatedMask = (
IIF ( ISNULL(PERMIT_STATUS, '') != ISNULL(#PERMIT_STATUS, ''), 4096, 0 ) +
IIF ( ISNULL(PERMIT_LOCATION, '') != ISNULL(#PERMIT_LOCATION, ''), 256, 0 ) +
...
)
I'm trying to solve simple optimization problem using SCIP but the method SCIPsolve returns exception.
The problem is: Minimize x + y + z
subject to: xyz = 1 where x, y and z are integers
The source code is given below. Does anybody have idea what's wrong with this code?
I tried this code in Visual Studio 2010 and 2012. I used the latest version of SCIP source code and libraries from http://scip.zib.de/
// 1. Initializing the SCIP environment
SCIP* scip;
SCIP_CALL(SCIPcreate(&scip));
// 2. Load all desired plugins
SCIP_CALL(SCIPincludeDefaultPlugins(scip));
// 3. Creating a problem
SCIP_CALL(SCIPcreateProb(scip, "Example", NULL, NULL, NULL, NULL, NULL, NULL, NULL));
// 4. Creating variables
SCIP_VAR *x, *y, *z;
SCIP_CALL(SCIPcreateVar(scip, &x, "x", -1, 1, 1.0, SCIP_VARTYPE_INTEGER, TRUE, FALSE, NULL, NULL, NULL, NULL, NULL));
SCIP_CALL(SCIPcreateVar(scip, &y, "y", -1, 1, 1.0, SCIP_VARTYPE_INTEGER, TRUE, FALSE, NULL, NULL, NULL, NULL, NULL));
SCIP_CALL(SCIPcreateVar(scip, &z, "z", -1, 1, 1.0, SCIP_VARTYPE_INTEGER, TRUE, FALSE, NULL, NULL, NULL, NULL, NULL));
// 5. Creating constraint
SCIP_EXPR* exprx;
SCIP_EXPR* expry;
SCIP_EXPR* exprz;
SCIP_CALL(SCIPexprCreate(SCIPblkmem(scip), &exprx, SCIP_EXPR_VARIDX, 0));
SCIP_CALL(SCIPexprCreate(SCIPblkmem(scip), &expry, SCIP_EXPR_VARIDX, 1));
SCIP_CALL(SCIPexprCreate(SCIPblkmem(scip), &exprz, SCIP_EXPR_VARIDX, 2));
/* setup monomial for x*y*z */
SCIP_Real exponents[3] = { 1.0, 1.0, 1.0 };
SCIP_EXPRDATA_MONOMIAL* monomial;
SCIP_Real one = 1.0;
SCIP_CALL(SCIPexprCreateMonomial(SCIPblkmem(scip), &monomial, one, 3, NULL, exponents));
/* create polynomial expression x*y*z */
SCIP_EXPR* expr;
SCIP_EXPR* children[3] = {exprx, expry, exprz};
SCIP_CALL(SCIPexprCreatePolynomial(SCIPblkmem(scip), &expr, 3, children, 1, &monomial, 0.0, FALSE));
/* setup expression tree with expr as root expression, the tree is defined w.r.t. 3 variables */
SCIP_EXPRTREE* exprtree;
SCIP_CALL(SCIPexprtreeCreate(SCIPblkmem(scip), &exprtree, expr, 3, 0, NULL));
/* assign SCIP variables to tree */
SCIP_VAR* vars[3] = { x, y, z };
SCIP_CALL(SCIPexprtreeSetVars(exprtree, 3, vars));
/* create and add nonlinear constraint x*y*z = 1 */
SCIP_CONS* constraint;
SCIP_CALL(SCIPcreateConsBasicNonlinear(scip, &constraint, "xyz", 0, NULL, NULL, 1, &exprtree, &one, 1.0, 1.0));
SCIP_CALL(SCIPaddCons(scip, constraint));
// 6. Solving the problem
SCIP_CALL(SCIPsolve(scip));
In Step 4, you miss the addition of the variables to SCIP (SCIPaddVar).
I currently have a stored procedure that updates files if they exist and inserts if they don't. The problem with the query below is it seem to be inserting all records regardless.
I can't seem to spot what the problem is?
Using SQL server 2012
ALTER PROC [dbo].[usp_UpdateInsertOptimise_new]
#Resid int = null,
#PostCode varchar(50),
#DriverID int,
#droporder int,
#X int,
#Y int,
#Calculate bit,
#uidref bigint,
#Description1 varchar(500),
#Description2 varchar(500),
#Description3 varchar(500),
#Uiddriver int,
#reservationsid int,
#Time varchar(50),
#TimeInPoint int,
#UniqueString varchar(50),
#DistanceBetweenTwoPoints float,
#Weight int,
#TimeBetweenPoints int,
#TimeFrom datetime,
#TimeTo datetime,
#TotalDistance float,
#Display varchar(150),
#Volume float,
#VehicleID int,
#Pallets int,
#AddressId int,
#CD nvarchar(10),
#ForkLiftRequired bit,
#HazardousRequired bit,
#FridgeRequired bit,
#TailLiftRequired bit,
#CurtinsideRequired bit,
#CDID varchar(50),
#CDOrder int,
#OriginalDate datetime,
#ArivalTime datetime,
#TimeForStage int,
#Optimise bit,
#ForVehicleGroupID int,
#DepotID int
AS
if EXISTS (SELECT * FROM optimise WITH (READUNCOMMITTED)
Where ReservationsID = #ResID)
BEGIN
UPDATE dbo.Optimise SET
PostCode = #PostCode,
[DriverID] = #DriverID,
[droporder] = #DropOrder,
[X] = #X,
[Y] = #Y,
[Calculate] = #Calculate,
[uidref] = #UIDRef,
[Description1] = #Description1,
[Description2] = #Description2,
[Description3] = #Description3,
[Uiddriver] = #UIDDriver,
[reservationsid] = #ReservationsID,
[Time] = #Time,
[TimeInPoint] = #TimeInPoint,
[UniqueString] = #UniqueString,
[DistanceBetweenTwoPoints] = #DistanceBetweenTwoPoints,
[Weight] = #Weight,
[TimeBetweenPoints] = #TimeBetweenPoints,
[TimeFrom] = #TimeFrom,
[TimeTo] = #TimeTo,
[TotalDistance] = #TotalDistance,
[Display] = #Display,
[Volume] = #Volume,
[VehicleID] = #VehicleID,
[Pallets] = #Pallets,
[AddressID] = #AddressID,
[CD] = #CD,
[ForkliftRequired] = #ForkLiftRequired,
[HazardousRequired] = #HazardousRequired,
[FridgeRequired] = #FridgeRequired,
[TailLiftRequired] = #TailLiftRequired,
[CurtinsideRequired] = #CurtinsideRequired,
[CDID] = #CDID,
[CDOrder] = #CDOrder,
[OriginalDate] = #OriginalDate,
[ArivalTime] = #ArivalTime,
[TimeForStage] = #TimeForStage,
[Optimise] = #Optimise,
[ForVehicleGroupID] = #ForVehicleGroupID,
[DepotID] = #DepotID
WHERE ReservationsID = #ResID
END
ELSE
IF NOT EXISTs(SELECT * FROM optimise WITH (READUNCOMMITTED)
Where ReservationsID = #ResID)
BEGIN
INSERT INTO [Optimise]
([PostCode],
[DriverID],
[droporder],
[X],
[Y],
[Calculate],
[uidref],
[Description1],
[Description2],
[Description3],
[Uiddriver],
[reservationsid],
[Time],
[TimeInPoint],
[UniqueString],
[DistanceBetweenTwoPoints],
[Weight],
[TimeBetweenPoints],
[TimeFrom],
[TimeTo],
[TotalDistance],
[Display],
[Volume],
[VehicleID],
[Pallets],
[AddressId],
[CD],
[ForkliftRequired],
[HazardousRequired],
[FridgeRequired],
[TailLiftRequired],
[CurtinsideRequired],
[CDID],
[CDOrder],
[OriginalDate],
[ArivalTime],
[TimeForStage],
[Optimise],
[ForVehicleGroupID],
[DepotID] )
VALUES (
#PostCode,
#DriverID,
#DropOrder,
#X,
#Y,
#Calculate,
#UIDRef,
#Description1,
#Description2,
#Description3,
#UIDDriver,
#ReservationsID,
#Time,
#TimeInPoint,
#UniqueString,
#DistanceBetweenTwoPoints,
#Weight,
#TimeBetweenPoints,
#TimeFrom,
#TimeTo,
#TotalDistance,
#Display,
#Volume,
#VehicleID,
#Pallets,
#AddressId,
#CD,
#ForkLiftRequired,
#HazardousRequired,
#FridgeRequired,
#TailLiftRequired,
#CurtinsideRequired,
#CDID,
#CDOrder,
#OriginalDate,
#ArivalTime,
#TimeForStage,
#Optimise,
#ForVehicleGroupID,
#DepotID)
END
GO
I Can't see anything wrong at all so sorry if this seems patronising, back to basics though:
Are you calling the correct SP? I notice the SP above is appended with _new usp_UpdateInsertOptimise_new
Are you passing the correct ResIDs? Do they exist, have you traced these when calling the proc.
simplify the proc to return a true/false, see which fires, remove anything not essential to just check if the ID exists or not. try switching IF EXISTS for IF NOT EXISTS see what happens.
#ResID is defaulted to null at the top. No idea why, it didn't work because of it though!