首页 > 解决方案 > 找不到列“dbo”或用户定义的函数或聚合“TryConvertInt”,或者名称不明确

问题描述

我称这个标量函数

CREATE FUNCTION dbo.TryConvertInt(@Value varchar(200))
RETURNS INT
AS
BEGIN
    SET @Value = REPLACE(@Value, ',', '')

    IF ISNUMERIC(@Value + 'e0') = 0 
       RETURN NULL

    IF (CHARINDEX('.', @Value) > 0 AND CONVERT(bigint, PARSENAME(@Value, 1)) <> 0) 
       RETURN NULL

    DECLARE @I bigint = CASE
                           WHEN CHARINDEX('.', @Value) > 0 
                              THEN CONVERT(bigint, PARSENAME(@Value, 2))
                              ELSE CONVERT(bigint, @Value)
                        END

    IF ABS(@I) > 2147483647 
        RETURN NULL

    RETURN @I
END
GO

在这个存储过程中

ALTER PROCEDURE [dbo].[SelectItem]
    @identifier VARCHAR(200)
AS
BEGIN
    SELECT
        tb_Items_Master.item_auto_code AS 'Item Code',
        tb_Items_Master.item_name_en AS 'Item Name',
        MIN(tb_Quantity_Expire.expity_date) AS 'Expiry',
        SUM(tb_Quantity_Expire.quantity) AS 'Stock',
        tb_Items_Master.price AS 'Price'
    FROM
        (tb_Items_Master
    INNER JOIN
        tb_Quantity_Expire ON tb_Items_Master.item_auto_code = tb_Quantity_Expire.item_auto_code
    LEFT JOIN
        tb_Items_Codes ON tb_Items_Master.item_auto_code = tb_Items_Codes.item_auto_code)
    WHERE
        tb_Items_Codes.item_code = @identifier
        OR tb_Items_Master.item_name_en LIKE '%'+@identifier+'%'
        OR tb_Items_Master.item_name_2 LIKE '%'+@identifier+'%'
        -- I'm calling it in the following line
        OR tb_Items_Master.item_auto_code = SELECT dbo.TryConvertInt(@identifier)
    GROUP BY
        tb_Items_Master.item_auto_code, tb_Items_Master.item_name_en,
        tb_Items_Master.price;
END

我得到错误

找不到列“dbo”或用户定义的函数或聚合“TryConvertInt”,或者名称不明确

我发现了类似的问题,但他们的回答没有帮助,或者有些事情我不知道

标签: sql-serveruser-defined-functions

解决方案


问题是tb_Items_Master.item_auto_code = select dbo.TryConvertInt(@identifier)。不确定这是标量函数还是表值函数。我假设前者,但我会发布你如何引用两者:

标量函数

tb_Items_Master.item_auto_code = dbo.TryConvertInt(@identifier)

表值函数

tb_Items_Master.item_auto_code = (SELECT dbo.TryConvertInt(@identifier))

或者

--In your `FROM` clause
CROSS APPLY dbo.TryConvertInt(@identifier) TCI
WHERE ...
   OR tb_Items_Master.item_auto_code = TCI.[column name] --I don't know what the name of the column returned it
                                                         --So you'll need to amend that

但是,该函数从其名称中暗示它是一个尝试将 a 转换varchar为 anint并且不会失败的函数?SQL Server 中已经有一个名为 的函数TRY_CONVERT,所以你可以这样做:

tb_Items_Master.item_auto_code = TRY_CONVERT(int,@identifier)

推荐阅读