/* 定義變量 */
DECLARE @ProductBarcode VARCHAR(38)
DECLARE @nCount INT/* 查詢記錄數 */
SELECT @nCount = COUNT(*) FROM (
SELECT ProductBarcode FROM Online_Stock --實時庫存表(記錄數為40萬條左右)
WHERE ProductBarcode = @ProductBarcode
UNION ALL 
SELECT ProductBarcode FROM PurchaseOrderDesc --採購訂單明細表(記錄數為10萬條左右)
WHERE ProductBarcode = @ProductBarcode
UNION ALL 
SELECT ProductBarcode FROM pRecord_2_2 --生產產出明細表(記錄數為60萬條左右)
WHERE ProductBarcode = @ProductBarcode) a/* 目的:我在刪除料號資料時,需要判斷此料號有沒有實時庫存表、採購訂單明細表、生產產出明細表中被使用過,如果有使用過不允許刪除 */

解决方案 »

  1.   

    select a.tid,count(a.tid) from 
    (select tid from 料号表 where tid not exists(select tid from 表1 where...) 
     union all
     select tid from 料号表 where tid not exists(select tid from 表2 where...)
     union all
     select tid from 料号表 where tid not exists(select tid from 表3 where...)) a
     group by a.tid having count(a.tid)=3
    肯定不好 - .- 偶素菜鸟 抛个砖
      

  2.   

    DECLARE @ProductBarcode VARCHAR(38)
    DECLARE @bbool int
    set bbool = 0
    IF EXISTS(SELECT 1 FROM SELECT ProductBarcode FROM Online_Stock
    WHERE ProductBarcode = @ProductBarcode)
     set bboo1 = 1
    IF EXISTS(SELECT 1 FROM SELECT ProductBarcode FROM PurchaseOrderDesc
    WHERE ProductBarcode = @ProductBarcode)
     set bboo1 = 1
    IF EXISTS(SELECT 1 FROM SELECT ProductBarcode FROM pRecord_2_2 
    WHERE ProductBarcode = @ProductBarcode)
     set bboo1 = 1
    IF bbool = 0
    DELTE 表1 WHERE  ProductBarcode = @ProductBarcode
      

  3.   

    在我的基礎上還能优化
    DECLARE @ProductBarcode VARCHAR(38)
    DECLARE @bbool int
    set bbool = 0
    IF EXISTS(SELECT 1 FROM SELECT ProductBarcode FROM Online_Stock
    WHERE ProductBarcode = @ProductBarcode)
     set bboo1 = 1
    if bboo1 = 0
    BEGIN
    IF EXISTS(SELECT 1 FROM SELECT ProductBarcode FROM PurchaseOrderDesc
    WHERE ProductBarcode = @ProductBarcode)
     set bboo1 = 1
    END
    IF bboo1 = 0
    BEGIN
    IF EXISTS(SELECT 1 FROM SELECT ProductBarcode FROM pRecord_2_2 
    WHERE ProductBarcode = @ProductBarcode)
     set bboo1 = 1
    END
    IF bbool = 0
    DELTE 表1 WHERE  ProductBarcode = @ProductBarcode
      

  4.   

    對,我正要講你的還可以優化.你的速度比我還快..
    我整理如下:
    -- 檢查當前料號是否已被使用
    -- 作者:yoncen 2007/08/10
    ALTER PROCEDURE chk_ProductBarcode_UseFlag
    (
    @ProductBarcode VARCHAR(38) --產品料號
    )
    AS
    SET NOCOUNT ONDECLARE @UseFlag BIT --使用標誌
    SET @UseFlag = 0IF EXISTS(SELECT * FROM Online_Stock --實時庫存
    WHERE ProductBarcode = @ProductBarcode)
    SET @UseFlag = 1IF @UseFlag = 0
    BEGIN
        IF EXISTS(SELECT * FROM PurchaseOrderDesc --採購表
    WHERE ProductBarcode = @ProductBarcode)
        SET @UseFlag = 1
    ENDIF @UseFlag = 0
    BEGIN
        IF EXISTS(SELECT * FROM pRecord_2_2 --涂布產出表
    WHERE ProductBarcode = @ProductBarcode)
        SET @UseFlag = 1
    ENDSELECT @UseFlag AS UseFlagSET NOCOUNT OFF已經解決!現在結貼..謝謝大家...