我在存储过程中有以下SQL查询并尝试调用表值函数(fn_get_type_ids)。我得到'必须声明标量变量" @ category_id"。'错误信息。表值函数返回多个ID。我该如何调用此功能? 如果我将硬编码值传递给函数,则存储过程有效。 dbo.fn_get_type_ids(2,90,NULL)。如果我传递下面显示的变量,它不起作用。可能有什么不对?请建议。
ALTER PROCEDURE [dbo].[get_search_results]
@user_id BIGINT,
@category_id INT = NULL,
@a_id INT = NULL,
@all_detail_id INT = NULL
AS
BEGIN
DECLARE @select_list VARCHAR(4000)
DECLARE @where_condition VARCHAR(4000)
SELECT @select_list = 'SELECT DISTINCT c.table1_id, c.table1_number, c.type_id '
SELECT @select_list = @select_list + ' FROM dbo.TABLE1 c '
SELECT @select_list = @select_list + ' LEFT JOIN TABLE2 cb ON cb.table1_id = c.table2_id '
SELECT @where_condition = ' WHERE c.active_flag = 1'
SELECT @where_condition = @where_condition + ' AND c.type_id in
(select type_id from dbo.fn_get_type_ids(@category_id, @a_id, @all_detail_id)) '
END
答案 0 :(得分:1)
您正在使用不同会话中存在的动态sql和sql变量,以使其工作,您需要将其更改为:
SELECT @where_condition = @where_condition + ' AND c.type_id in (select type_id from dbo.fn_get_type_ids('+CAST(@category_id as varchar))+', '+CAST(@a_id as varchar))+', '+CAST(@all_detail_id as varchar))+')) '
答案 1 :(得分:0)
尝试进行最后一次选择:
SELECT @where_condition = @where_condition + ' AND c.type_id in
(select type_id from dbo.fn_get_type_ids(' + ISNULL(@category_id,'NULL') + ', ' + ISNULL(@a_id,'NULL') + ', ' + ISNULL(@all_detail_id,'NULL') + ')) '