Link to home
Start Free TrialLog in
Avatar of raymurphy
raymurphy

asked on

Trying to understand how CROSS APPLY works

Asked to support a new application in SQL 2005, and came across some code which works fine - but was just wondering if anyone could give a detailed breakdown of how this code works.

Specific functionality is a function which will break down a long single-line description (of up to 4000 chars) into multiple smaller chunks of VARCHAR(40).

Here is the function :

CREATE FUNCTION [dbo].[SplitColumnLength]
(
      @ID INT,
      @Split VARCHAR(4000),
      @Length INT
)
RETURNS @Values TABLE
(
      [ID] INT,
      [RowID] INT,
      [Value] VARCHAR(500)
)
AS
BEGIN
      IF @Split IS NOT NULL
      BEGIN
            DECLARE @Index INT,
            @Loop INT

            SET @Index = 0
            SET @Loop = (SELECT CEILING(CONVERT(FLOAT, LEN(@Split)) / CONVERT(FLOAT, @Length)))

            WHILE @Index < @Loop
            BEGIN
                  INSERT INTO @Values VALUES(@ID, @Index + 1, SUBSTRING(@Split, (@Index * @Length) + 1, @Length))
                  SET @Index = @Index + 1
            END
      END
      RETURN
END

and the application code joins to this function in SQL Server 2005 using CROSS APPLY - e.g. to split customer description into VARCHAR(40) chunks, it uses the following :
      -- SELECT s.RowID, s.Value
      -- FROM CustomerDetails b
      -- CROSS APPLY dbo.SplitColumnLength(b.CustomerNo, b.CustomerDescription, 40) s

As I say, the code works fine - but to understand it, I was hoping someone could give a breakdwon of how the function itself works, and then how the associated CROSS APPLY use of that function (as per the above example) also works.

Thanks.
ASKER CERTIFIED SOLUTION
Avatar of chapmandew
chapmandew
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
no points  just participating in discussion with this ref article:
http://www.codeguru.com/vb/vbnet30/article.php/c15845/
Avatar of raymurphy
raymurphy

ASKER

Thanks for that, chapmandrew ....
Had been hoping for a more detailed breakdown, but thanks for the comments - much appreciated