我目前正在努力解决SQL查询问题。我想知道有人能提供帮助吗?
我正在尝试将字符串传递给存储过程之一并基于此我想在WHERE子句中稍微修改查询
param字符串可以是Alphabets或Category ID
ALTER procedure [dbo].[procProductShow]
@Alphabet varchar(3) = 'ALL'
AS
IF @Alphabet = 'ALL' or @Alphabet = 'A' OR @Alphabet = 'B' OR @Alphabet = 'C' --- UNTIL Z
SELECT
Product.ProdID,
Product.ProdImgThumbnailLoc,
Product.ProdImgThumbnailAltText
FROM
ProductCategory
INNER JOIN Product ON ProductCategory.ProdID = Product.ProdID
INNER JOIN Category ON ProductCategory.CatID = Category.CatID
WHERE
Product.ProdShowOnWeb = 1 AND
Category.ShowOnReport = 1 AND
(@Alphabet = 'ALL' OR Product.ProdHeading LIKE @Alphabet + '%')
ORDER BY Product.ProdHeading
ELSE
SELECT
Product.ProdID,
Product.ProdImgThumbnailLoc,
Product.ProdImgThumbnailAltText
FROM
ProductCategory
INNER JOIN Product ON ProductCategory.ProdID = Product.ProdID
INNER JOIN Category ON ProductCategory.CatID = Category.CatID
WHERE
Product.ProdShowOnWeb = 1 AND
Category.ShowOnReport = 1 AND
Category.CatId = @Alphabet
ORDER BY Product.ProdHeading
答案 0 :(得分:0)
您实际上可以简化此查询,以便您不需要执行长IF语句:
ALTER procedure [dbo].[procProductShow]
@Alphabet varchar(3) = 'ALL'
AS
SELECT
Product.ProdID,
Product.ProdImgThumbnailLoc,
Product.ProdImgThumbnailAltText
FROM
ProductCategory
INNER JOIN Product ON ProductCategory.ProdID = Product.ProdID
INNER JOIN Category ON ProductCategory.CatID = Category.CatID
WHERE
Product.ProdShowOnWeb = 1 AND
Category.ShowOnReport = 1 AND
(@Alphabet = 'ALL'
OR (@Alphabet LIKE '[A-Z]' AND Product.ProdHeading LIKE @Alphabet + '%')
OR Category.CatId = @Alphabet)
ORDER BY Product.ProdHeading
WHERE条件的@Alphabet LIKE '[A-Z]'
部分将执行正则表达式以检查@Alphabet是否仅包含' A'通过' Z'