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 MBR_UPR_ID=@MBR_ID and MBR_LEG_POS=@LEG_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 值“Flife1”转换为数据类型 int 时转换失败。

4

3 回答 3

2

这很奇怪。你有什么数据MBR_UPR_ID?如果它是 varchar,那么您不应该得到错误,如果它是int- 为什么要尝试将其与varcharFlife1 进行比较?

我的建议:

  • 格式化你的代码!你为什么这么讨厌空间?无法读取以 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 中有所有列名。我还建议删除查询中的所有演员表,没有它应该可以正常工作

于 2013-08-19T08:55:23.603 回答
1

尝试以下修复:

--code before the union
FROM MBR_MST 
WHERE CAST(MBR_UPR_ID AS VARCHAR(100)) =@MBR_ID AND MBR_LEG_POS=@LEG_POS           
UNION ALL
--rest of the code
于 2013-08-19T08:53:49.137 回答
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;
于 2016-03-05T00:57:57.187 回答