我有一个带有,的customer
表格,并且搜索基于以上三个中的任何一个或全部。Cust_Id
Name
City
我应该去哪一个?
动态 SQL:
declare @str varchar(1000) set @str = 'Select [Sno],[Cust_Id],[Name],[City],[Country],[State] from Customer where 1 = 1' if (@Cust_Id != '') set @str = @str + ' and Cust_Id = ''' + @Cust_Id + '''' if (@Name != '') set @str = @str + ' and Name like ''' + @Name + '%''' if (@City != '') set @str = @str + ' and City like ''' + @City + '%''' exec (@str)
简单查询:
select [Sno],[Cust_Id],[Name],[City],[Country],[State] from Customer where (@Cust_Id = '' or Cust_Id = @Cust_Id) and (@Name = '' or Name like @Name + '%') and (@City = '' or City like @City + '%')
我应该更喜欢哪一个(1或2),有什么优势?
经过大家的建议,这就是我终于得到的。
DECLARE @str NVARCHAR(1000)
DECLARE @ParametersDefinition NVARCHAR(500)
SET @ParametersDefinition = N'@InnerCust_Id varchar(10),
@InnerName varchar(30),@InnerCity varchar(30)'
SET @str = 'Select [Sno],[Cust_Id],[Name],[City],[Country],[State]
from Customer where 1 = 1'
IF(@Cust_Id != '')
SET @str = @str + ' and Cust_Id = @InnerCust_Id'
IF(@Name != '')
SET @str = @str + ' and Name like @InnerName'
IF(@City != '')
SET @str = @str + ' and City like @InnerCity'
-- ADD the % symbol for search based upon the LIKE keyword
SELECT @Name = @Name + '%', @City = @City+ '%'
EXEC sp_executesql @str, @ParametersDefinition,
@InnerCust_Id = @Cust_Id,
@InnerName = @Name,
@InnerCity = @City;
注意:@Cust_Id
和是传递给存储过程的@Name
参数 @City
参考:http: //blogs.lessthandot.com/index.php/DataMgmt/DataDesign/changeing-exec-to-sp_executesql-doesn-tp