我正在写一个网站上使用的查询。当需要查询时,它直接被解析到服务器,结果全部由查询控制。该网站只是返回表格。我在网站上做的是客户端可以选择的复选框,并将这些复选框解析为查询@var = 1
或@var = 0
。正因为如此,现在我有这个代码来检查和添加或不取决于它是否被检查。我的问题是,有没有更好的办法去这比使用IF
声明是这样,因为我有代码的几个部分,其中包括这样的:比使用IF更适合这种情况吗?
SET @sql = 'select distinct '
If @mgchk = 1
SET @sql = @sql + 'p.MainGroup'
If @sgchk = 1 and @sql = 'select distinct '
SET @sql = @sql + 'p.SubGroup'
If @sgchk = 1 and @sql not like '%SubGroup'
SET @sql = @sql + ',p.SubGroup'
If @ssgchk = 1 and @sql = 'select distinct '
SET @sql = @sql + 'p.SubSubGroup'
If @ssgchk = 1 and @sql not like '%SubSubGroup'
SET @sql = @sql + ',p.SubSubGroup'
If @Seasonchk = 1 and @sql = 'select distinct '
SET @sql = @sql + 'p.Season'
If @Seasonchk = 1 and @sql not like '%Season'
SET @sql = @sql + ',p.Season'
If @vendorchk = 1 and @sql = 'select distinct '
SET @sql = @sql + 'p.VendorID'
If @vendorchk = 1 and @sql not like '%VendorID'
SET @sql = @sql + ',p.VendorID'
SET @sql =
@sql +
' into
##aa
from
RPProducts p,
RPIv i,
RPTrsd d,
RPTrs s
WHERE
s.StoreID = d.StoreID and
s.ReceiptNO = d.ReceiptNO and
i.UPC = d.UPC and
i.StoreID = d.StoreID and
i.IVProduct = p.Productid and
s.TRSdate >= '''+ convert(varchar(10), @trsfrom, 101) +''' and
s.TRSdate <= '''+ convert(varchar(10), @trsto, 101) +''''
execute sp_executesql @sql
@mgchk/@sgchk/@ssgchk/@seasonchk/@vendorchk是复选框变量
要回答@Aaron,
全局临时因为动态查询。整个查询得到处理并在数据被拖动时立即丢弃。没有冲突会发生在那里。
我的日期变量是datetime
,它在动态SQL中给我一个错误。
是的,回想一下同样的事情来检查,这是整个问题的原因,如果有更好的使用比IF
检查。
,我发现使用别名连接更容易...
哦哇,这么多东西在这里挑选...全球##临时表,为什么?日期为区域字符串,为什么?为什么要检查你添加的列是否是第一个?旧式连接,为什么? – 2013-02-28 15:28:47
@AaronBertrand - 更新后的答案 – JohnZ 2013-02-28 15:39:09
你有没有试过让两个用户同时运行这个存储过程?关于你称之为“别名连接”的内容 - [请阅读本文全文,包括评论](http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits-to-kick-using -old的风格,joins.aspx)。 – 2013-02-28 15:40:39