我需要一个函数,但似乎无法正确使用它,我已经在这里和其他地方查看了示例,似乎无法正确得到这个,我需要一个可选项包含在我的查询中,我有这个查询(有效):
SELECT TOP 100 PERCENT SKU, Description, LEN(CONVERT(VARCHAR
(1000),Description)) AS LenDesc FROM tblItem
WHERE Title = @Title AND Manufacturer = @Manufacturer
ORDER BY LenDesc DESC
这在一个函数中有效,但是制造商对于此搜索是可选的 - 这是为了找到类似项目的描述,如果不存在,则另一个查询是:
SELECT TOP 100 PERCENT SKU, Description, LEN(CONVERT(VARCHAR
(1000),Description)) AS LenDesc FROM tblItem
WHERE Title = @Title ORDER BY LenDesc DESC
哪个缺少制造商,如何让我的功能使用基于制造商价值的查询或不存在。 原因是我将有一个函数首先检查SKU的描述,如果它不存在 - 它使用此方法从类似产品获取描述,然后使用类似产品的描述更新正在添加的产品。
这是迄今为止的功能:
ALTER FUNCTION [dbo].[GetDescriptionByTitleManufacturer]
(
@Title varchar(400),
@Manufacturer varchar(160)
)
RETURNS TABLE
AS
RETURN (
SELECT TOP 100 PERCENT SKU, Description, LEN(CONVERT(VARCHAR
(1000),Description)) AS LenDesc FROM tblItem
WHERE Title = @Title AND Manufacturer = @Manufacturer
ORDER BY LenDesc DESC
)
我尝试过添加BEGIN和IF ... ELSE,但每次尝试都会遇到错误或语法问题,我希望能够做一些像这样的伪函数(这不起作用):
ALTER FUNCTION [dbo].[GetDescriptionByTitleManufacturer]
(
@Title varchar(400),
@Manufacturer varchar(160)
)
RETURNS TABLE
AS
BEGIN
IF (@Manufacturer = Null)
RETURN (
SELECT TOP 100 PERCENT SKU, Description, LEN(CONVERT(VARCHAR
(1000),Description)) AS LenDesc FROM tblItem
WHERE Title = @Title ORDER BY LenDesc DESC
)
ELSE
RETURN (
SELECT TOP 100 PERCENT SKU, Description, LEN(CONVERT(VARCHAR
(1000),Description)) AS LenDesc FROM tblItem
WHERE Title = @Title AND Manufacturer = @Manufacturer
ORDER BY LenDesc DESC
)
END
答案 0 :(得分:4)
你可以这样做吗?
ALTER FUNCTION [dbo].[GetDescriptionByTitleManufacturer]
(
@Title varchar(400),
@Manufacturer varchar(160)
)
RETURNS TABLE
AS
RETURN (
SELECT TOP 100 PERCENT SKU, Description, LEN(CONVERT(VARCHAR
(1000),Description)) AS LenDesc FROM tblItem
WHERE Title = @Title AND (@Manufacturer IS NULL OR Manufacturer = @Manufacturer)
ORDER BY LenDesc DESC
)
答案 1 :(得分:1)
执行AND (Manufacturer = @Manufacturer OR @Manufacturer IS NULL)
时,您将无法使用索引。动态搜索有许多微妙的性能影响,您应该阅读Dynamic Search Conditions in T-SQL by Erland Sommarskog
如果您拥有正确的SQL Server 2008版本(SQL 2008 SP1 CU5(10.0.2746)及更高版本),则可以使用此小技巧实际使用索引:
将OPTION (RECOMPILE)
添加到您的查询see Erland's article,SQL Server将根据本地值创建查询计划之前从OR
内解析(@Manufacturer IS NULL OR Manufacturer = @Manufacturer)
变量和索引都可以使用。
ALTER FUNCTION [dbo].[GetDescriptionByTitleManufacturer]
(
@Title varchar(400),
@Manufacturer varchar(160)
)
RETURNS TABLE
AS
RETURN
(SELECT TOP 100
PERCENT SKU, Description, LEN(CONVERT(VARCHAR(1000),Description)) AS LenDesc
FROM tblItem
WHERE Title = @Title
AND (@Manufacturer IS NULL OR Manufacturer = @Manufacturer)
ORDER BY LenDesc DESC
OPTION (RECOMPILE) ---<<<<only valid for SQL 2008 SP1 CU5 (10.0.2746) and later
)
GO
答案 2 :(得分:0)
当制造商不适用时,您可以尝试使用NULL:
SELECT TOP 100 PERCENT SKU, Description, LEN(CONVERT(VARCHAR
(1000),Description)) AS LenDesc FROM tblItem
WHERE Title = @Title AND (Manufacturer = @Manufacturer OR @Manufacturer IS NULL)
ORDER BY LenDesc DESC