我执行时遇到以下错误。
Msg 137,Level 15,State 2,Line 2 必须声明标量变量“@user_name”。
(1行受影响)
USE [qcsl]
GO
/****** Object: StoredProcedure [dbo].[UserAdvancedSearch] Script Date: 3/31/2017 12:09:22 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[UserAdvancedSearch]
-- Add the parameters for the stored procedure here
(
@user_name varchar(50) = NULL,
@role_id int = 2,
@user_status int = 1
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
DECLARE @query varchar(2000);
SET @query = 'select * from user_main
where (CONCAT(user_first_name,user_last_name) like CONCAT(@user_name) OR CONCAT(CONCAT(user_first_name,user_last_name) IS NULL)
AND
(user_role_id_ref=@role_id OR user_role_id_ref IS NULL)
AND
(user_status = @user_status OR user_status IS NULL)';
EXEC(@query)
END
答案 0 :(得分:0)
由于您在动态查询中有参数,因此请修改您的执行查询,如下所示并尝试。
EXEC SP_EXECUTESQL @query,N' @user_name varchar(50),@role_id INT,@user_status int',@user_name=@user_name,@role_id=@role_id,@user_status=user_status
此外,修改您的代码行
DECLARE @query varchar(2000);
到
DECLARE @query nvarchar(2000);