该名称不是有效的标识符。动态存储过程错误

the name is not a valid identifier. error in dynamic stored procudure

我的存储过程是:

ALTER PROCEDURE  [dbo].[Asbabbazi_A]
    @name_product nvarchar(50),
    @first_price int,
    @final_price int,
    @collection_1 nvarchar(30),
    @id_state tinyint
AS
BEGIN
DECLARE @SQLstring nvarchar(1000)
DECLARE @PARAMS nvarchar(1000)  
set @SQLstring = 'SELECT IDproduct,name_product,first_price,final_price,max_registered_price,
                  date_record_shamsi,final_date_view_shamsi,
                   count_views,image_1,collection_1 from Table_asbabbazi where active=0 '
if(@name_product != 'no name')
set @SQLstring = @SQLstring + ' AND (name_product  LIKE %@name_product%)'
if (@final_price != 0)
set @SQLstring = @SQLstring +  ' AND ( first_price between  @first_price AND @final_price )'
if (@collection_1 != 'انتخاب کنید')
set @SQLstring = @SQLstring + ' AND (collection_1 = @collection_1  )'

if (@id_state != 0)
set @SQLstring = @SQLstring + ' AND (id_state = @id_state  )'

execute @SQLstring
END

执行时显示此错误: 名称'SELECT IDproduct,name_product,first_price,final_price,max_registered_price, date_record_shamsi,final_date_view_shamsi, count_views,image_1,collection_1 来自 Table_asbabbazi 其中 active=0 AND (name_product LIKE %@name_product%) AND (collection_1 = @collection_1 )' 不是有效标识符。 请帮忙

您将变量放在引号内,从而使它们成为字符串文字。而不是这种事情:

set @SQLstring = @SQLstring + ' AND (collection_1 = @collection_1  )'

你需要这样的东西:

set @SQLstring = @SQLstring + ' AND (collection_1 = ' 
+ @collection_1  + ' )'

查询字符串中的某些参数未正确解析,您正在使用动态 sql 它必须由 EXECUTE sp_executesql 语句执行。这是执行动态 sql:

的正确方法
ALTER PROCEDURE  [dbo].[Asbabbazi_A]
    @name_product nvarchar(50),
    @first_price int,
    @final_price int,
    @collection_1 nvarchar(30),
    @id_state tinyint
AS
BEGIN
DECLARE @SQLstring nvarchar(1000)
DECLARE @PARAMS nvarchar(1000)  
set @SQLstring = 'SELECT IDproduct,name_product,first_price,final_price,max_registered_price,
                  date_record_shamsi,final_date_view_shamsi,
                   count_views,image_1,collection_1 from Table_asbabbazi where active=0 '
if(@name_product != 'no name')
set @SQLstring = @SQLstring + ' AND name_product  LIKE ''%' + @name_product  + '%''' + ' '
if (@final_price != 0)
set @SQLstring = @SQLstring +  ' AND first_price between  ' + CONVERT(nvarchar(1000), @first_price)  + ' AND ' + CONVERT(nvarchar(1000), @final_price) + ' '
if (@collection_1 != 'انتخاب کنید')
set @SQLstring = @SQLstring + ' AND collection_1 = ''' + @collection_1 + ''' '

if (@id_state != 0)
set @SQLstring = @SQLstring + ' AND id_state = ' + CONVERT(nvarchar(1000), @id_state) + ' '

EXECUTE sp_executesql @SQLstring
END

简而言之,

像这样执行存储过程时,将声明的 SQLstring 放在括号内

执行 usp_executeSql (@SQLstring)

示例:

错 ❌

EXECUTE usp_executeSql @SQLstring

正确✔

EXECUTE usp_executeSql (@SQLstring)