存储过程强制转换

时间:2015-02-12 08:19:53

标签: sql-server-2008 stored-procedures

我对以下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  

基本上我必须用逗号分隔的值拆分一个字符串,对于这些值的每一个,我执行一个查询并将结果放在另一个以逗号分隔的字符串中。 如果我将这些值作为存储过程参数发送,(&#34; 5220,3008,1561,2678,&#34; 5 )我收到错误,< em>&#34;无法投射nvarchar值&#39; 5220,3008,1561,2678&#39;输入int&#34; 。 但是如果我在存储过程中将这些值构建为:

    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 :(得分:0)

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