Home Forums SQL Server 2012 SQL Server 2012 - T-SQL How to call a stored proc once per each row of a table, without using CURSOR RE: How to call a stored proc once per each row of a table, without using CURSOR

  • From what I can gather, there is no need for a cursor. It can change depending on the actual work required!

    😎

    USE tempdb;

    GO

    IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.ROUTINES

    WHERE ROUTINE_NAME = 'MyMainiTVF'

    AND ROUTINE_SCHEMA = 'dbo')

    DROP FUNCTION dbo.MyMainiTVF;

    GO

    -- All this proc does is, prints out the list of parameters that are passed to it.

    CREATE FUNCTION dbo.MyMainiTVF (

    @IDINT,

    @NameVARCHAR (200),

    @SessionIDINT

    )

    RETURNS TABLE

    AS

    RETURN

    -- Alright!...let me show the world what my parameter values are :)

    SELECT'SessionID - '

    + CAST (@SessionID AS VARCHAR (20))

    + ' called MyMainiTVF with ID: '

    + CAST (@ID AS VARCHAR (20))

    + '; and Name: ' + @Name AS RET_VAL

    GO

    /* CREATE TEST SET */

    DECLARE @TestTable TABLE (ID INT, Name VARCHAR (200))

    INSERT @TestTable VALUES (1, 'AAA'), (2, 'BBB'), (3, 'CCC'), (4, 'DDD')

    /* THE SELECT */

    SELECT

    XTV.RET_VAL

    FROM @TestTable TT

    CROSS APPLY dbo.MyMainiTVF(TT.ID,TT.Name,@@SPID) AS XTV

    Results

    RET_VAL

    -----------------------------------------------------------

    SessionID - 54 called MyMainiTVF with ID: 1; and Name: AAA

    SessionID - 54 called MyMainiTVF with ID: 2; and Name: BBB

    SessionID - 54 called MyMainiTVF with ID: 3; and Name: CCC

    SessionID - 54 called MyMainiTVF with ID: 4; and Name: DDD