我正在尝试使用IF else如果内联表中的逻辑值为SQL的函数并返回基于该逻辑的containsstable。但我有IF Else IF块的语法问题。谢谢您的帮助。因为我不能参数化containsstable中的列,所以我不得不求助于使用if else语句。这是代码。感谢。
我正在
Msg 156,Level 15,State 1,Procedure FullTextSearch,第17行 关键字“IF”附近的语法不正确。
ALTER FUNCTION [dbo].[FullTextSearch]
(
@Columns nvarchar(100), @SearchPhrase nvarchar(100)
)
RETURNS TABLE
AS
RETURN
IF (@Columns='Title')
BEGIN
SELECT *
from projects as P inner join
containstable(PROJECTS, Title, @SearchPhrase) as K
on P.project_id = K.[KEY]
END
ELSE IF (@Columns='Project_Details')
BEGIN
SELECT *
from projects as P inner join
containstable(PROJECTS, Project_Details, @SearchPhrase) as K
on P.project_id = K.[KEY]
END
ELSE IF (@Columns='Contact_Info')
BEGIN
SELECT *
from projects as P inner join
containstable(PROJECTS, Contact_Info, @SearchPhrase) as K
on P.project_id = K.[KEY]
END
ELSE IF (@Columns='Project_Description')
BEGIN
SELECT *
from projects as P inner join
containstable(PROJECTS, Project_Description, @SearchPhrase) as K
on P.project_id = K.[KEY]
END
ELSE -- (@Columns='All')
BEGIN
SELECT *
from projects as P inner join
containstable(PROJECTS, (Title, Project_Details, Contact_Info, Project_Description), @SearchPhrase) as K
on P.project_id = K.[KEY]
END
答案 0 :(得分:2)
您收到此错误是因为您尝试在内联表值函数中使用多个语句。
内联表值函数必须包含单个SELECT
语句,类似于:
CREATE FUNCTION dbo.MyInlineFunction (@MyParam INT)
RETURNS TABLE
AS
RETURN
(
SELECT first_column, second_column FROM ...
)
您的函数需要声明为多语句函数,语法类似于:
CREATE FUNCTION dbo.MyMultiStatementFunction (@MyParam INT)
RETURNS @MyTable TABLE
(
first_column INT, second_column VARCHAR(100) -- etc
)
AS
BEGIN
IF (@MyParam = 1)
INSERT INTO @MyTable (...)
SELECT ... FROM ...
ELSE
INSERT INTO @MyTable (...)
SELECT ... FROM ...
RETURN
END
答案 1 :(得分:0)
首先,你在第一个IF而不是=
上有==哦,是的,我注意到你在ELSE的CONTAINSTABLE参数中列出了两次ProjectDetails
如果您正在搜索特定字段,可以使用以下语法:
WHERE Title LIKE '%'+ @Search +'%'
OR ProjectDetails LIKE '%' + @Search + '%'
OR ContactInfo LIKE '%' + @Search + '%')
(警告)此语法忽略任何索引。
您可以查看此blog以获取适用于索引的解决方案。它似乎有一个很好的解决方案。
答案 2 :(得分:0)
查看sql management studio的多语句功能模板,即菜单:View-> Template Explorer-创建多语句表值函数。
问题是多语句功能的语法不同。还要注意,正如jmein所说的那样,第一个if =。