我存储的原因是:
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, 来自Table_asbabbazi的count_views,image_1,collection_1,其中active = 0 AND(name_product LIKE%@ name_product%)AND(collection_1 = @ collection_1)'不是有效的标识符。 请帮忙
答案 0 :(得分:0)
你的变量在引号内,从而使它们成为字符串文字。而不是这种事情:
set @SQLstring = @SQLstring + ' AND (collection_1 = @collection_1 )'
你需要这样的东西:
set @SQLstring = @SQLstring + ' AND (collection_1 = '
+ @collection_1 + ' )'
答案 1 :(得分:0)
查询字符串中的某些参数未正确解析,并且您使用的是动态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