Home Forums SQL Server 2008 T-SQL (SS2K8) how to replace this cursor with set based solution? RE: how to replace this cursor with set based solution?

  • polkadot (9/26/2013)


    I'm trying to apply what I've learned in the APPLY links you left me, Luis, to my solution. Thus, I want a TVF for the right half of the query. By right half, I mean the query to the right of the OUTER APPLY which gets the createdate for each bench in the input field.

    I'm getting error when I try to create the function:

    CREATE FUNCTION GetBench (@bench varchar(20))

    RETURNS TABLE

    WITH SCHEMABINDING

    AS RETURN

    SELECT r.createdate

    FROM Runs r

    INNER JOIN runs_machines rm ON rm.runid = r.runid

    INNER JOIN Machines m ON m.machineid = rm.machineid

    WHERE m.NAME LIKE (@bench + '[0-9][0-9][0-9]')

    AND r.createdate > dateadd(M, - 3, getdate())

    error:

    Msg 4512, Level 16, State 3, Procedure GetBench, Line 5

    Cannot schema bind table valued function 'GetBench' because name 'Runs' is invalid for schema binding. Names must be in two-part format and an object cannot reference itself.

    Can you point out what's wrong in the TVF? Thanks.

    The error message is telling you exactly what the problem is, You MUST use 2 part naming when using schemabinding.

    From BOL:

    SCHEMABINDING

    Binds the view to the schema of the underlying table or tables. When SCHEMABINDING is specified, the base table or tables cannot be modified in a way that would affect the view definition. The view definition itself must first be modified or dropped to remove dependencies on the table that is to be modified. When you use SCHEMABINDING, the select_statement must include the two-part names (schema.object) of tables, views, or user-defined functions that are referenced. All referenced objects must be in the same database.

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/