转换[T-SQL / SQL Server]时转换失败

时间:2017-07-28 08:50:16

标签: sql-server stored-procedures

每次我尝试调用我的存储过程时,都会收到以下错误:

  

Msg 245,Level 16,State 1,Procedure P_KB_GET_GK_UEBERSICHT,第16行

     

将varchar值'diverse'转换为数据类型int时转换失败。

某些示例值(或示例调用)如下所示:

exec P_KB_GET_GK_UEBERSICHT '','','','','D2335548','','Lindner',''

我根本不明白这个错误信息。他在diverse中提到了什么。此外,转换为INT会出现什么问题?第二个和最后一个参数是INT,但即使没有单引号,错误消息也保持不变。

为了给你提供所有信息,我将添加存储过程。

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[P_KB_GET_GK_UEBERSICHT]
@status tinyint, @jahr int, @cl_vnr bigint, @cl_name nvarchar(50), @sgi nvarchar(20), @gknr nvarchar(4), @gkname varchar(50), @gueltjahr int

AS

if @cl_vnr = '' set @cl_vnr = 0
if @status = '' set @status = 0
if @jahr = '' set @jahr = 0
if @gueltjahr = '' set @gueltjahr = '0'
if @gknr = '' set @gknr = '0'
if @gknr IS NULL set @gknr = '0'


if @gueltjahr = '0'
    select distinct CL_ID, CD_CLVID, CD_VERSION, CL_NAME, CD_JAHR, ST_NAME as CD_STATUS,
        case isNULL(CD_AKTIV,0) when 0 then 'Nein' when 1 then 'Ja' end as CD_AKTIV,
        CD_STATUS as CD_STATUS_ID, CD_VON, CD_BIS 
    from dbo.V_KB_CLUSTER d
    inner join dbo.V_KB_CLUSTER_GK k on d.CD_CLVID = k.KD_CLVID
    left join dbo.T_KB_GK_STATUS on CD_STATUS = ST_ID
    where   d.CL_ART = 'GK'
            and CD_STATUS = case when @status = 0 then CD_STATUS else @status end
            and CD_JAHR = case when @jahr = 0 then CD_JAHR else @jahr end
            and CD_CLVID = case when @cl_vnr = 0 then CD_CLVID else @cl_vnr end
            and CL_NAME like '%' + @cl_name + '%'
            and k.KD_NR = case when @gknr = '0' then k.KD_NR else @gknr end
            and k.GK_KUNDE like '%' + @gkname + '%'
    order by CL_ID, CD_JAHR DESC, CD_VERSION DESC
else
    select distinct CL_ID, CD_CLVID, CD_VERSION, CL_NAME, CD_JAHR, ST_NAME as CD_STATUS,
        case isNULL(CD_AKTIV,0) when 0 then 'Nein' when 1 then 'Ja' end as CD_AKTIV,
        CD_STATUS as CD_STATUS_ID, CD_VON, CD_BIS 
    from dbo.V_KB_CLUSTER d
    inner join dbo.V_KB_CLUSTER_GK k on d.CD_CLVID = k.KD_CLVID
    left join dbo.T_KB_GK_STATUS on CD_STATUS = ST_ID
    where   d.CL_ART = 'GK'
            and CD_STATUS = case when @status = 0 then CD_STATUS else @status end
            and CD_JAHR = case when @jahr = 0 then CD_JAHR else @jahr end
            and CD_CLVID = case when @cl_vnr = 0 then CD_CLVID else @cl_vnr end
            and CL_NAME like '%' + @cl_name + '%'
            and k.KD_NR = case when @gknr = '0' then k.KD_NR else @gknr end
            and k.GK_KUNDE like '%' + @gkname + '%'
            and @gueltjahr between year(CD_VON) and isNULL(year(CD_BIS),@gueltjahr)
    order by CL_ID, CD_JAHR DESC, CD_VERSION DESC 

我正在使用SQL-Server 2008。

更新:它也不适用于数值:

exec P_KB_GET_GK_UEBERSICHT 0,0,0,'','D2335548','','Lindner',0

1 个答案:

答案 0 :(得分:1)

您对存储过程的调用是错误的。对于前三个参数,SQL Server分别需要tinyint,int和bigint,但是你传递''被解释为varchar。看看你的proc,如果你想要默认值,我认为你需要将所有三个传递为0。

编辑

你的SQL错了。取代

if @gueltjahr = '0'

使用

if @gueltjahr = 0