将单个值从SQL传递到Access多次

时间:2013-12-04 20:00:02

标签: sql sql-server-2008 inline scalar

我有一个过程来检查多个select语句的记录数,并根据查询的数量返回一个值...

  -- check aDT
    If ((SELECT DISTINCT theFN, theIN, theLN, theANA FROM aDT
        WHERE theFN = @pF  and theIN = @pI 
        and theLN = @pL  and theANA = @pLY) > 0)
        BEGIN
            SET @Bool = 1
            RETURN @Bool
        END 

    -- check aDT2
    If ((SELECT theFN, theIN, theLN, theANA FROM aDT2
        GROUP BY theFN, theIN, theLN, theANA 
        HAVING theFN = @pF  and theIN = @pI 
        and theLN = @pL  and theANA = @pLY) > 0)
        BEGIN
            SET @Bool = 1
            RETURN @Bool
        END 

IF (EXISTS(SELECT DISTINCT tblFs.fldFN, tblFs.fldRN, tblFs.fldIN, tblUs.fldPK,
        tblUs.fldLN, tblUA.fldANA, 
        tblUA.fldMT, (CASE WHEN (IsNull([flddate1], '') = '') THEN [flddate2] 
        ELSE [flddate1] END) AS fldDate, tblUA.fldPG
        FROM tblUA INNER JOIN tblUs ON tblUA.fldULK = tblUs.
        fldUID INNER JOIN tblFs ON tblUs.fldFK = tblFs.fldFID 
        WHERE (tblFs.fldFN = @pF) AND (tblFs.fldIN = @pI ) AND (tblUs.
        fldLN = @pL ) AND (tblUA.fldANA = @pL)  
        BEGIN
            SET @sDup = 1
            RETURN @sDup
        END

我有多个查询,如果其中任何一个返回记录,则位值设置为1,否则将其设置为0,并且该值始终返回到MS Access。不幸的是,每次运行的功能越来越慢;使用表值函数是一个更好的选择吗?

更新:我将该函数配置为表值内联函数,它甚至更慢。非常慢。我只是不确定如何以更有效的方式实现我需要的结果。

1 个答案:

答案 0 :(得分:1)

由于您只对是否存在记录感兴趣,因此您可以放弃所有昂贵的运营商,用更便宜的替代品替换它们:

If ( EXISTS (
    SELECT * FROM aDT WHERE theFN = @pF and theIN = @pI and theLN = @pL and theANA = @pLY
))
    BEGIN
        SET @Bool = 1
        RETURN @Bool
    END 

If ( EXISTS (
    SELECT * FROM aDT2 WHERE theFN = @pF and theIN = @pI and theLN = @pL and theANA = @pLY
))
    BEGIN
        SET @Bool = 1
        RETURN @Bool
    END 

IF ( EXISTS (
    SELECT *
    FROM tblUA
    INNER JOIN tblUs ON tblUA.fldULK = tblUs.fldUID
    INNER JOIN tblFs ON tblUs.fldFK = tblFs.fldFID 
    WHERE (tblFs.fldFN = @pF) AND (tblFs.fldIN = @pI ) AND (tblUs.fldLN = @pL ) AND (tblUA.fldANA = @pL)
))
    BEGIN
        SET @sDup = 1
        RETURN @sDup
    END

结果应该相当于没有DISTINCTGROUP BY / HAVING,因为您的结果是二进制:DISTINCT / GROUP BY子句可以更改记录计数,但它们无法更改EXISTS运算符的结果。