2011-01-31 68 views
0

我有一個下面的sql函數,它將一個字符串單詞作爲輸入,然後檢查單詞是否等於一個categoryName或不是我希望它的行爲像if語句爲true它從環打破,並否則返回0或1我該怎麼辦,即時通訊新的SQL腳本plz幫助返回@temp_catid ...以下是我的函數break和return @temp_catid if(true)

USE [myDB] 
GO 

/****** Object: UserDefinedFunction [dbo].[udfisEqualToCategory] Script Date: 01/31/2011 10:57:56 ******/ 
SET ANSI_NULLS ON 
GO 

SET QUOTED_IDENTIFIER ON 
GO 




Create FUNCTION [dbo].[udfisEqualToCategory](@word nvarchar(max)) 
RETURNS INT 

AS 
BEGIN 
--declare a temp category table for data processing 
declare @temptbl_category Table 
(
indexx int identity(1,1), 
categoryid int, 
categoryname nvarchar(max) 
) 
--insert data from feedcrawler.category into temp category table 
insert into @temptbl_category 
select CategoryId,Name 
from Category 

--declare some variables to hold the data of current row of temp category table being processed while looping 

declare @temp_catid int 
declare @temp_catname nvarchar(max) 
declare @rowcount int 
set @rowcount=(select count(indexx)from @temptbl_category) 



declare @I int 
set @I=1 

--print'given string-> '+ @FullName 
--print'string length-> '+convert(nvarchar(max),@strlen) 
while(@I <= @rowcount) 
begin 

select @temp_catname=categoryname,@temp_catid=categoryid from @temptbl_category where [email protected] 
set @temp_catname=lower(@temp_catname) 
if(@[email protected]_catname) 
begin 
return @temp_catid 
break 
end--end if 

set @[email protected]+1 

END--while loop ends 
return 0 
end-- function ends 

GO 
+1

我知道省略標點符號可以節省我在輸入時的時間,但當他們讀取它時需要其他時間沒有冒犯只是一個觀察 – 2011-01-31 07:08:13

回答

0

無需環路,只是搜索表與WHERE

Create FUNCTION [dbo].[udfisEqualToCategory](@word nvarchar(max)) 
RETURNS INT 
AS 
BEGIN 
    declare @temp_catid int 

    select 
     @temp_catid = categoryid 
    from 
     Category 
    WHERE 
     LOWER(@word) = LOWER(categoryname); 

    --no match = @temp_catid IS NULL. So change to zero 
    RETURN ISNULL(@temp_catid, 0); 
END 
GO 
+0

TNN很像一個魅力工作... – Rafay 2011-01-31 06:43:35