TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Devendra Kumar
NA
500
162.9k
Optimize sql query
Sep 19 2020 10:37 AM
Hi everone
I had creating a billing application and needs to calculate the balance qty,
I am having 5 tables
stock
purchase
PurchaseReturn
Sale
SalesReturn
I want the balanceQty (based on ItemCode, which is common) in stock table and for that I had created a scalar function and used it as formula of computed column, now the issue is the number of rows is getting huge (approx 5000 as of now) and it is taking much time to return the rows more than 2 minutes.
Function
ALTER
FUNCTION
[dbo].[GetClosingStock]
(
--Add the parameters for the function here
@ItemCode nvarchar(
max
)
)
RETURNS
decimal
(18, 3)
AS
BEGIN
--Declare the return variable here
DECLARE
@sQty
decimal
(18, 3), @pQty
decimal
(18, 3), @prQty
decimal
(18, 3), @saleQty
decimal
(18, 3), @srQty
decimal
(18, 3)
DECLARE
@Result
decimal
(18, 3)
-- Add the T - SQL statements to compute the return value here
Select
@sQty = (
select
ISNULL
(
sum
(qty), 0)
from
Stock
where
ItemCode = @ItemCode)
Select
@pQty = (
select
ISNULL
(
sum
(qty), 0)
from
Purchase
where
ItemCode = @ItemCode)
select
@prQty = (
select
ISNULL
(
sum
(qty), 0)
from
PurchaseReturn
where
ItemCode = @ItemCode)
select
@saleQty = (
select
ISNULL
(
sum
(qty), 0)
from
Sale
where
ItemCode = @ItemCode)
select
@srQty = (
select
ISNULL
(
sum
(qty), 0)
from
SalesReturn
where
ItemCode = @ItemCode)
select
@Result = (@sQty + (@pQty - @prQty) - (@saleQty - @srQty))
-- Return the result of the function
RETURN
@Result
END
;
How can I optimize it to perform better or guide me to calculate the ClosingStockQty in a much better way.
Does StoreProcedure helps me out or anything
Thanks
Devendra
Reply
Answers (
7
)
Quartile Number for group
store procedur in Sql Server