如何为以下代码创建存储过程。
use Test
DECLARE @Str VARCHAR(120)
SET @Str = 'company name'
DECLARE @End INT
DECLARE @Split INT
SET @Split = 40
declare @SomeTable table
(
Content varchar(120)
)
WHILE (LEN(@Str) > 0)
BEGIN
IF (LEN(@Str) > @Split)
BEGIN
SET @End = LEN(LEFT(@Str, @Split)) - CHARINDEX(' ', REVERSE(LEFT(@Str, @Split)))
INSERT INTO @SomeTable VALUES (RTRIM(LTRIM(LEFT(LEFT(@Str, @Split), @End))))
SET @Str = SUBSTRING(@Str, @End + 1, LEN(@Str))
END
ELSE
BEGIN
INSERT INTO @SomeTable VALUES (RTRIM(LTRIM(@Str)))
SET @Str = ''
END
END
SELECT *
FROM @SomeTable
答案 0 :(得分:2)
将其转换为存储过程的最简单方法是:
use Test
CREATE PROCEDURE [dbo].[IGotSomeoneonStackOverflowToWriteThisforMe]
AS
DECLARE @Str VARCHAR(120)
SET @Str = 'company name'
DECLARE @End INT
DECLARE @Split INT
SET @Split = 40
declare @SomeTable table
(
Content varchar(120)
)
WHILE (LEN(@Str) > 0)
BEGIN
IF (LEN(@Str) > @Split)
BEGIN
SET @End = LEN(LEFT(@Str, @Split)) - CHARINDEX(' ', REVERSE(LEFT(@Str, @Split)))
INSERT INTO @SomeTable VALUES (RTRIM(LTRIM(LEFT(LEFT(@Str, @Split), @End))))
SET @Str = SUBSTRING(@Str, @End + 1, LEN(@Str))
END
ELSE
BEGIN
INSERT INTO @SomeTable VALUES (RTRIM(LTRIM(@Str)))
SET @Str = ''
END
END
SELECT *
FROM @SomeTable
GO
EXEC [dbo].[IGotSomeoneonStackOverflowToWriteThisforMe]
答案 1 :(得分:1)
CREATE PROCEDURE dbo.ThisIsNotHard
@Str VARCHAR(120),
@Split INT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @SomeTable table
(
Content VARCHAR(120)
);
WHILE (LEN(@Str) > 0)
BEGIN
IF (LEN(@Str) > @Split)
BEGIN
SET @End = LEN(LEFT(@Str,@Split))-CHARINDEX(' ',REVERSE(LEFT(@Str, @Split)));
INSERT @SomeTable(Content) SELECT RTRIM(LTRIM(LEFT(LEFT(@Str,@Split),@End)));
SET @Str = SUBSTRING(@Str,@End+1,LEN(@Str));
END
ELSE
BEGIN
INSERT @SomeTable(Content) SELECT RTRIM(LTRIM(@Str));
SET @Str = '';
END
END
SELECT Content FROM @SomeTable;
END
GO
现在你可以这样称呼它:
EXEC dbo.ThisIsNotHard @Str = 'Company name', @Split = 40;