我需要一个函数,但似乎无法完全正确,我已经查看了此处和其他地方的示例,但似乎无法正确理解,我需要在我的查询中包含一个可选项目,我有这个查询(有效):
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
)
结尾