SQL Server函数根据参数返回不同的select语句

时间:2020-11-26 16:28:35

I need a function that returns different select statements based on the value of the parameter. I wrote it like below but it throws an error like

我需要一个函数,它根据参数的值返回不同的select语句。我写的如下,但它会抛出一个错误

A RETURN statement with a return value cannot be used in this context.

带有返回值的RETURN语句不能在此上下文中使用。

ALTER FUNCTION [dbo].[Sample] (@SampleValue int)
RETURNS TABLE
AS
BEGIN
IF @SampleValue=100
RETURN(
 SELECT ....
)
ELSE
RETURN(
 SELECT ....

)

1 个解决方案

#1


3  

Per your comments - just write it as a single query - there's no need to write it out twice.

根据您的意见 - 只需将其作为单个查询编写 - 无需将其写出两次。

ALTER FUNCTION [dbo].[Sample] (@SampleValue int)
RETURNS TABLE
AS
BEGIN
RETURN(
 SELECT .... WHERE @SampleValue = 100 OR (<rest of where clause from other branch>)
)

#1


3  

Per your comments - just write it as a single query - there's no need to write it out twice.

根据您的意见 - 只需将其作为单个查询编写 - 无需将其写出两次。

ALTER FUNCTION [dbo].[Sample] (@SampleValue int)
RETURNS TABLE
AS
BEGIN
RETURN(
 SELECT .... WHERE @SampleValue = 100 OR (<rest of where clause from other branch>)
)