【发布时间】:2014-03-11 08:41:50
【问题描述】:
我读到一个回答说您不想在 SQL Server 中使用 WHILE 循环。我不明白这种概括。我对 SQL 还很陌生,所以我可能还不明白解释。我还读到除非必须,否则您并不想使用游标。我发现的搜索结果对所提出的问题过于具体,我无法从中收集到有用的技术,所以我将这个提供给您。
我要做的是获取客户端文件中的值并在必要时缩短它们。这里有几件事需要实现。我不能简单地破解提供的字段值。我的公司有要使用的标准缩写。我把这些放在一个表中,缩写。该表有LongName 和ShortName。我不想简单地缩写行中的每个LongName。只要字段长度太长,我只想应用更新。这就是我需要WHILE 循环的原因。
我的思考过程是这样的:
CREATE FUNCTION [dbo].[ScrubAbbrev]
(@Field nvarchar(25),@Abbrev nvarchar(255))
RETURNS varchar(255)
AS
BEGIN
DECLARE @max int = (select MAX(stepid) from Abbreviations)
DECLARE @StepID int = (select min(stepid) from Abbreviations)
DECLARE @find varchar(150)=(select Longname from Abbreviations where Stepid=@stepid)
DECLARE @replace varchar(150)=(select ShortName from Abbreviations where Stepid=@stepid)
DECLARE @size int = (select max_input_length from FieldDefinitions where FieldName = 'title')
DECLARE @isDone int = (select COUNT(*) from SizeTest where LEN(Title)>(@size))
WHILE @StepID<=@max or @isDone = 0 and LEN(@Abbrev)>(@size) and @Abbrev is not null
BEGIN
RETURN
REPLACE(@Abbrev,@find,@replace)
SET @StepID=@StepID+1
SET @find =(select Longname from Abbreviations where Stepid=@stepid)
SET @replace =(select ShortName from Abbreviations where Stepid=@stepid)
SET @isDone = (select COUNT(*) from SizeTest where LEN(Title)>(@size))
END
END
显然RETURN 应该放在最后,但我需要将我的变量重置为下一个@stepID、@find 和@replace。
这是我必须使用光标(我还没有写过)的时候吗?
【问题讨论】:
标签: sql sql-server function loops while-loop