-5

如何为以下代码创建存储过程。

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
4

2 回答 2

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]
于 2013-10-24T13:01:01.483 回答
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;
于 2013-10-24T13:43:29.557 回答