2013-08-19 147 views
0

我的存儲過程是:轉換失敗

CREATE PROCEDURE [dbo].[USP_GET_MBR_DWN_DTL] (@MBR_ID VARCHAR(50), @LEG_POS CHAR)  
AS BEGIN  

WITH CTE(MBR_ID, MBR_LEG_POS, MBR_NM, MBR_JOIN_TT, LVL, MBR_UPR_ID, MBR_SPR_ID) AS    
(   
     SELECT 
      CAST(MBR_ID AS VARCHAR(100)) as MBR_ID, 
      MBR_LEG_POS, MBR_NM, MBR_JOIN_TT, 
      CAST(MBR_UPR_ID AS VARCHAR(100)) as MBR_UPR_ID, 
      CAST(MBR_SPR_ID AS VARCHAR(100)) as MBR_SPR_ID, 
      LVL=0 
     FROM MBR_MST 
     WHERE [email protected]_ID and [email protected]_POS  

     UNION ALL    

     SELECT 
      CAST(M.MBR_ID AS VARCHAR(100)) as MBR_ID, 
      M.MBR_LEG_POS,M.MBR_NM,M.MBR_JOIN_TT, 
      CAST(M.MBR_UPR_ID AS VARCHAR(100)) as MBR_UPR_ID, 
      CAST(M.MBR_SPR_ID AS VARCHAR(100)) as MBR_SPR_ID, 
      LVL+1 
     FROM MBR_MST M 
      JOIN CTE F ON CAST(M.MBR_UPR_ID AS VARCHAR(100))=CAST(F.MBR_ID AS VARCHAR(100))  
)  
SELECT * FROM CTE ORDER BY LVL, MBR_JOIN_TT OPTION (MAXRECURSION 0)  
END 

但是當我運行

USP_GET_MBR_DWN_DTL 'Flife1', 'A' 

它顯示錯誤

消息245,第16層,狀態1,程序USP_GET_MBR_DWN_DTL,第5行
轉換失敗轉換varchar v將'Flife1'轉換爲數據類型int。

+0

請幫助..這對我造成很多問題.. – Nisar

+2

MBR_UPR_ID和MBR_LEG_POS的類型是什麼? –

回答

2

這是非常奇怪的。 MBR_UPR_ID有什麼數據?如果它的varchar比你不應該得到一個錯誤,如果它是一個int - 你爲什麼試圖與varchar Flife1比較?

我的建議:

  • 格式的代碼!你爲什麼這麼討厭空間?讀取以blob編寫的查詢是不可能的。請記住,其他開發人員可能需要閱讀和更改代碼,如果您要編寫這樣的代碼,他們會詛咒您;
  • 看看你的表中的數據類型。我會說,如果你在加入之前必須進行轉換,那麼你做錯事的可能性很大;

更新啊!找到了。你在你的CTE聲明剛剛混合域:

WITH CTE(MBR_ID,MBR_LEG_POS,MBR_NM,MBR_JOIN_TT,LVL,MBR_UPR_ID,MBR_SPR_ID) AS 

應該

WITH CTE(MBR_ID,MBR_LEG_POS,MBR_NM,MBR_JOIN_TT,MBR_UPR_ID,MBR_SPR_ID,LVL) AS 

但是你可以寫只是with CTE - 你有你的CTE中的所有列名。我也建議刪除您在您的查詢都投,應該還好吧工作,而它

+0

MBR_UPR_ID是varchar(50) – Nisar

+0

檢查我更新的答案。你只是在cte聲明中混合了列。 –

0

下面是突出你的UNION兩個表之間的差異一個方便查詢:

SELECT 
    c1.ordinal_position, 
    c1.table_name, 
    c1.data_type, 
    c1.column_name, 
    c2.column_name, 
    c2.data_type, 
    c2.table_name 
FROM INFORMATION_SCHEMA.COLUMNS c1 
LEFT JOIN (
    SELECT ordinal_position, column_name, table_name,data_type 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_NAME = N'TABLE_ONE') c2 on c1.ordinal_position = c2.ordinal_position 
where c1.TABLE_NAME = N'TABLE_TWO' 
and (c1.column_name <> c2.column_name 
    or c1.data_type <> c2.data_type) 
order by c1.ordinal_position asc;