由于业务规则最近发生了变化,一组数据过去常常存储在一个数据库中,现在存储在同一服务器上的不同数据库中。当前设置的东西,如果用户想要查询与业务规则更改时间重叠的日期范围内的数据,他们将被迫在其代码中使用IF语句。
我想创建一个表值函数,它将为进行此类查询的用户抽象业务规则中的此更改。目前我正在尝试执行与此类似的代码:
CREATE FUNCTION dbo.someFunction (date DATETIME)
RETURNS TABLE
AS
RETURN
IF (date <= business_rules_change_date)
BEGIN
SELECT (A select statement)
FROM (Old Database)
WHERE (criteria)
END
ELSE
SELECT (A similar select statement)
FROM (New Database)
JOIN (A Join Statement)
WHERE (criteria)
GO
我被告知IF语句周围存在语法错误。我的问题有一个很好的解决方案吗?
答案 0 :(得分:1)
您可以尝试这样的事情
CREATE FUNCTION dbo.someFunction (date DATETIME)
RETURNS @RtnTable TABLE (SomeValue varchar(250))
AS
BEGIN
IF (date <= business_rules_change_date)
BEGIN
INSERT INTO @RtnTable
SELECT (A select statement)
FROM (Old Database)
WHERE (criteria)
END
ELSE
BEGIN
INSERT INTO @RtnTable
SELECT (A similar select statement)
FROM (New Database)
JOIN (A Join Statement)
WHERE (criteria)
END
RETURN
END
此示例假定您的函数返回带有单个varchar列的结果集。根据您的IF条件,您可以使用不同的SELECT语句的结果填充它。根据需要进行调整。
答案 1 :(得分:1)
或者正如Yuriy建议你可以使用像这样的多语句表值函数...
CREATE FUNCTION dbo.someFunction (date DATETIME)
RETURNS @TABLE TABLE
(
-- Define the structure of table here
)
AS
BEGIN
IF (date <= business_rules_change_date)
BEGIN
INSERT INTO @TABLE
SELECT (A select statement)
FROM (Old Database)
WHERE (criteria)
END
ELSE
BEGIN
INSERT INTO @TABLE
SELECT (A similar select statement)
FROM (New Database)
JOIN (A Join Statement)
WHERE (criteria)
END
RETURN
END
答案 2 :(得分:0)
内联表值函数不能包含IF语句。您可以这样重新组织查询:
CREATE FUNCTION dbo.someFunction (date DATETIME)
RETURNS TABLE
AS
RETURN
SELECT (A select statement)
FROM (Old Database)
WHERE (criteria) AND (date <= business_rules_change_date)
UNION
SELECT (A similar select statement)
FROM (New Database)
JOIN (A Join Statement)
WHERE (criteria) AND (date > business_rules_change_date)
GO