我写道,无法在此查询中修复从varchar到int的类型转换问题

时间:2014-09-03 05:52:29

标签: sql sql-server tsql

我需要帮助来修复一个类型转换问题,这个问题在我写的sp上几个小时就困扰我。我想像这个'12 / SH / IFCR / 7'那样拆分账单号码并得到最后一个int值并单独存储

EG。 '12/SH/IFCR/7' - > 12/SH/IFCR/和7

注意:12/SH/IFCR/是前缀,它保持不变但最后一个号码更改

ALTER PROCEDURE spGenerateCreditInvoiceForApi 
        @ShopId as int,
        @TransId as int
        --@CompanyId as int
AS
BEGIN
        SET NOCOUNT ON;

        declare @CompanyId as int
        declare @Prefix as varchar(50)
        declare @ProformaId as int
        declare @MaxId as int
        declare @FinId as int
        declare @InvoiceNo as varchar(150)

        set @CompanyId=(select CompanyID from aShops where ShopID=@ShopId)

        set @FinId=(Select financialid from afinancialyear where  Curfinancialyear = 1 and companyid = @CompanyId)

        set @Prefix=(SELECT  Prefix FROM aPrefix WHERE InterfaceID = 1504 and ShopId=@ShopId and FinancialId = @FinId)

        set @ProformaId=(select ISNULL(MAX(CONVERT(INT,REVERSE(LEFT((REVERSE(ihInvoiceNo)),(PATINDEX('%/%' ,(REVERSE (ihInvoiceNo))))-1)))),0)
         from LOsInvoiceHeader
         where ihInvoiceID= @TransId and ihShopID=@ShopId)

        --SET @intBillID = (SELECT CASE WHEN COUNT(poshBillid)=0 THEN 1 ELSE MAX(poshBillid)+1 END FROM losposheader WHERE poshShopID=@intShopId)

        set  @MaxId=(SELECT CASE WHEN COUNT(ihInvoiceNo)=0 THEN 1
         ELSE MAX(ihInvoiceNo)+1 END 
        from losinvoiceheader
        where ihShopId =@ShopId and ihfinancialid=@FinId and ihType='I')

        SET @InvoiceNo = (@Prefix+CONVERT(VARCHAR,@MaxId)) 

        --update LOsInvoiceHeader set ihInvoiceNo=@InvoiceNo, ihProformaID=@ProformaId where ihInvoiceID=@TransId and ihShopID=@ShopId

        --print @InvoiceNo
    END
    GO

错误:

  

Msg 245,Level 16,State 1,Procedure spGenerateCreditInvoiceForApi,Line 33
  将varchar值'12 / SH / IFCR / 7'转换为数据类型int时,转换失败。

提前致谢。

2 个答案:

答案 0 :(得分:1)

这样的事情

declare @bill varchar(50),
 @reversebill varchar(50),
  @reverseResult varchar(50)

select @bill = '12/SH/IFCR/73'
select @reversebill = REVERSE(@bill)
select @reverseResult = SUBSTRING(@reversebill,0,CHARINDEX('/',@reversebill))

select Reverse(@reverseResult)

答案 1 :(得分:1)

感谢上帝,我发现了问题

我将Max()的使用更改为count()并将转换方法添加到整个查询

<强>之前

set  @MaxId=(SELECT CASE WHEN COUNT(ihInvoiceNo)=0 THEN 1
         ELSE MAX(ihInvoiceNo)+1 END 
        from losinvoiceheader
        where ihShopId =@ShopId and ihfinancialid=@FinId and ihType='I')

<强>后

set  @MaxId=CONVERT(INT,(SELECT CASE WHEN COUNT(ihInvoiceNo)=0 THEN 1
     ELSE CONVERT(INT,COUNT(ihInvoiceNo)+1) END 
    from losinvoiceheader
    where ihShopId =@ShopId and ihfinancialid=@FinId and ihType='I'))