![](/img/trans.png)
[英]Using user defined function (UDF) in where clause more than once with running the function only once
[英]Running SQL user defined function that returns boolean, in where clause
希望這似乎不太簡單。 我看了這個,但我不太擅長SQL用戶定義的函數及其使用,所以我不確定發生了什么。 為了告訴我為什么我收到錯誤,他們想了幾點:
在期望條件的上下文中指定的非布爾類型的表達式,在')'附近。
為了這:
UPDATE LMI_Contact
SET Phone = NULL
WHERE dbo.LMI_IsSingleCharacterRepeated(Phone, '0')
可以使用以下方法創建函數:
-- ***this will also find NULL and empty string values***
CREATE FUNCTION LMI_IsSingleCharacterRepeated (@string varchar(max), @char char(1))
RETURNS bit
AS
BEGIN
DECLARE @index int
DECLARE @len int
DECLARE @currentChar char(1)
SET @index = 1
SET @len= LEN(@string)
WHILE @index <= @len
BEGIN
SET @currentChar = SUBSTRING(@string, @index, 1)
IF @currentChar = @char
SET @index= @index+ 1
ELSE
RETURN 0
END
RETURN 1
END;
GO
此函數用於檢查字符串是否是任何指定的單個字符,重復。 希望有人發現它有用!
即使返回類型為bit
也必須對函數使用比較運算符。
UPDATE LMI_Contact
SET Phone = NULL
WHERE dbo.LMI_IsSingleCharacterRepeated(Phone, '0') = 1
試試這個
CREATE FUNCTION LMI_IsSingleCharacterRepeated (@str varchar(max), @char char(1))
RETURNS BIT
AS
BEGIN
DECLARE @indx int
DECLARE @len int
DECLARE @currentChar char(1)
SET @indx = 1
SET @len= LEN(@str)
WHILE @indx <= @len
BEGIN
SET @currentChar = SUBSTRING(@str, @indx, 1)
IF @currentChar = @char
SET @indx= @indx+ 1
ELSE
RETURN 0
END
RETURN 1
END;
GO
您需要將查詢的where子句修改為:
UPDATE LMI_Contact
SET Phone = NULL
WHERE dbo.LMI_IsSingleCharacterRepeated(Phone, '0') = 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.