Search code examples
sql-serverstored-proceduresazure-sql-databaseuser-defined-functionsuser-defined-types

How to do ForEach on user defined table type in SQL Server stored procedure?


XX PROCEDURE [dbo].[XXX]
    @X dbo.IntType readonly
AS
BEGIN
    SET NOCOUNT ON;
    // how can I foreach(@X) here and do process individually?
END

IntType is a user-defined table type

CREATE TYPE [dbo].[IntType] AS TABLE(
    [T] [int] NOT NULL,
    PRIMARY KEY CLUSTERED 
(
    [T] ASC
)

I need to use this in SQL Azure, please advice.


Solution

  • Cursors are the SQL equivalent of ForEach,

    But cursors are often a sign of bad SQL: they violate the usual set-based thinking that SQL is built on and optimized for.

    Search on SQL cursor or SQL Cursor Azure for many examples, tutorials and optimization notes.

    But it can't be said enough: avoid cursors: they are often the crutch for programmers from other languages in SQL and they are often slow and hard to maintain.