Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Function only single time for multiple places in a query

Tags:

sql

sql-server

SQL Query

SELECT
    dbo.TotalPackagedQty(t1.int_PackingListDetailId),
    float_Quantity,
    int_PackingListDetailId
        CASE
            WHEN dbo.TotalPackagedQty(t1.int_PackingListDetailId) = 0 THEN 1
            WHEN dbo.TotalPackagedQty(t1.int_PackingListDetailId) < float_Quantity THEN 2
            WHEN dbo.TotalPackagedQty(t1.int_PackingListDetailId) = float_Quantity THEN 3
        END
FROM tblSdPackingListDetail t1
WHERE int_PackingId = '10901032014121313496PM0'

This is a sql query.

I am using a function with the name dbo.TotalPackagedQty(t1.int_PackingListDetailId).

I am using this function 4 times in query. Output is coming correct, but i want to call this function only single time to increase speed of the query.

Kindly suggest me a better option in query not stored procedure or other things.

like image 909
Ankit Jain Avatar asked Jan 03 '14 07:01

Ankit Jain


People also ask

Can we use where clause two times in SQL?

But yes, you can use two WHERE.

Can we call function in select statement?

A function can be called in a select statement as well as in a stored procedure. Since a function call would return a value we need to store the return value in a variable.


1 Answers

Try this one -

SELECT
    value,
    float_Quantity,
    int_PackingListDetailId =
                CASE
                    WHEN value = 0 THEN 1
                    WHEN value < float_Quantity THEN 2
                    WHEN value = float_Quantity THEN 3
                END
FROM dbo.tblSdPackingListDetail t1
CROSS APPLY (
    SELECT value = dbo.TotalPackagedQty(t1.int_PackingListDetailId)
) tt
WHERE int_PackingId = '10901032014121313496PM0'
like image 146
Devart Avatar answered Nov 14 '22 21:11

Devart