首页 文章

存储过程强制转换

提问于
浏览
0

我对以下SP有一个奇怪的问题:

CREATE PROCEDURE [dbo].[Manufacturer_GetProductsCountByManufacturedId]
(
    @ManufacturerIds NVARCHAR(MAX) = '',
    @ExcludeType INT
)
AS
BEGIN   
    DECLARE @ManufacturerId NVARCHAR(MAX)
    DECLARE @GoodManufacturerIds NVARCHAR(MAX) = ''
    DECLARE @result BIGINT  
    DECLARE @pos INT
    DECLARE @len INT

    SET @GoodManufacturerIds = ''
    SET @pos = 0
    SET @len = 0

    WHILE CHARINDEX(',', @ManufacturerIds, @pos + 1)>0
    BEGIN
        -- Split
        SET @len = CHARINDEX(',', @ManufacturerIds, @pos+1) - @pos
        SET @ManufacturerId = SUBSTRING(@ManufacturerIds, @pos, @len)

        -- Check
        SELECT TOP 1 @result = p.ProductId
        FROM [MYDB].[dbo].[Product] p
        INNER JOIN [MYDB].[ProductTyping].[TypedProductFieldValue] tpfv ON tpfv.ProductId = p.ProductId
        WHERE ManufacturerId = @ManufacturerId 
        AND tpfv.ProductTypeId <> @ExcludeType    

        IF @result > 0
            SET @GoodManufacturerIds = @GoodManufacturerIds + @ManufacturerId + ','
        SET @pos = CHARINDEX(',', @ManufacturerIds, @pos+@len)+1
    END
    -- Last comma kaputt
    SET @GoodManufacturerIds = LEFT(@GoodManufacturerIds, LEN(@GoodManufacturerIds) - 1)

    RETURN @GoodManufacturerIds
END

基本上我必须用逗号分隔的值拆分一个字符串,对于每个值,我执行一个查询并将结果放在另一个以逗号分隔的字符串中 . 如果我将这些值作为存储过程参数发送,( "5220,3008,1561,2678,"5 )我收到错误,"Unable to cast nvarchar values '5220,3008,1561,2678' to type int" . 但是如果我在存储过程中将这些值构建为:

DECLARE @ManufacturerId NVARCHAR(MAX)
    DECLARE @GoodManufacturerIds NVARCHAR(MAX) = ''
    DECLARE @result BIGINT  
    DECLARE @pos INT
    DECLARE @len INT

    -- test
    DECLARE @ManufacturerIds NVARCHAR(MAX) = ''
    DECLARE @ExcludeType INT    
    SET @ManufacturerIds = '5220,3008,1561,2678,13715,5047,'
    SET @ExcludeType = 5

    SET @GoodManufacturerIds = ''
    SET @pos = 0
    SET @len = 0

    WHILE CHARINDEX(',', @ManufacturerIds, @pos + 1)>0
    BEGIN
        -- Split
        SET @len = CHARINDEX(',', @ManufacturerIds, @pos+1) - @pos
        SET @ManufacturerId = SUBSTRING(@ManufacturerIds, @pos, @len)

        -- Check
        SELECT TOP 1 @result = p.ProductId
        FROM [MYDB].[dbo].[Product] p
        INNER JOIN [MYDB].[ProductTyping].[TypedProductFieldValue] tpfv ON tpfv.ProductId = p.ProductId
        WHERE ManufacturerId = @ManufacturerId 
        AND tpfv.ProductTypeId <> @ExcludeType    

        IF @result > 0
            SET @GoodManufacturerIds = @GoodManufacturerIds + @ManufacturerId + ','
        SET @pos = CHARINDEX(',', @ManufacturerIds, @pos+@len)+1
    END
    -- Last comma kaputt
    SET @GoodManufacturerIds = LEFT(@GoodManufacturerIds, LEN(@GoodManufacturerIds) - 1)

    RETURN @GoodManufacturerIds

一切正常,我得到了新的字符串 . 我不知道错误可能在第一个程序中,任何提示?

1 回答

  • 0

    我发现错误,我正在使用RETURN但RETURN是整数值,在这种情况下我的是一个字符串,所以把SELECT一切正常 .

相关问题