SQL函数转换为内联

时间:2014-09-16 21:35:28

标签: sql sql-server sql-function

我在存储过程中有一个函数,它使我的sql从1秒到10-14秒。有人可以帮助我将它们合并到一个内联函数中,这样我的sql就会大大加快。

INSERT INTO
    #tempTable
SELECT DISTINCT
    PRODUCT.name,
    dbo.getProductTopImage(PRODUCT.name) as image
FROM
    dbo.PRODUCT

getProductTopImage函数

CREATE FUNCTION dbo.getProductTopImage
(
    @PRODUCTNAME VARCHAR(255)
)
RETURNS VARCHAR(255)
AS
BEGIN
    DECLARE @IMAGE AS VARCHAR(255)
    DECLARE @ID AS INT

    SELECT TOP 1
        @IMAGE = PRODUCT.image,
        @ID = PRODUCT.id
    FROM
        PRODUCT
    WHERE
        PRODUCT.name = @PRODUCTNAME

    IF @IMAGE IS NULL   
        BEGIN
            SET @IMAGE = dbo.func_getImageRefs(@ID, 1)
        END

    RETURN @IMAGE
END

func_getImageRefs函数

CREATE FUNCTION dbo.func_getImageRefs
    (
        @ProductId AS INT,
        @Place AS INT
    )
RETURNS VARCHAR(20)
AS

    BEGIN
    DECLARE @REF AS VARCHAR(20)
    SET @REF = '0'
        SELECT 
            @REF = PLANTIMAGE.imageRef
            FROM PRODUCT
                LEFT OUTER JOIN
            dbo.PLANTIMAGE
        ON
            dbo.PRODUCT.hls = PLANTIMAGE.plantid
            WHERE PRODUCT.id = @ProductId AND PLANTIMAGE.imageNum = @Place

            RETURN @REF
    END

1 个答案:

答案 0 :(得分:3)

如果我正确理解您的问题,我认为您根本不需要使用这些功能。

with cte as (
    select *, 
        row_number() over (partition by name order by id) rn
    from product
)
select 
    c.name, 
    coalesce(c.image, pi.imageref)
from cte c
    left join plantimage pi on c.hls = pi.plantid and pi.imageNum = 1
where c.rn = 1

这会创建一个公用表表达式来存储row_number()。使用该字段,您可以镜像SELECT TOP 1语句。然后你可以使用COALESCE并加入plantimage表。如果product表中的图像为null,则它将返回plantimage表中的图像(如果存在)。您还需要将部分WHERE条件移至JOIN以维持OUTER JOIN