Search code examples
sqlsql-servert-sqlsql-function

Check and Return rows if SQL Server table exists


I am working on an application that involves SQL Server tables. I am writing a query in which I need to check for a table and if the table exists I need to select records from that table and if the table does not exist in that database that I need to select from a different table.

I tried with writing the same with UDF but I am not successful. I am unable to use a stored procedure as I need to get the output to be joined to another table.

Is there any way to do this?

CREATE FUNCTION dbo.udf_school_information 
    (@univ_id INT)
RETURNS @returntable TABLE
(
    univ_id INT,
    school_number INT,
    school_name NVARCHAR(255),
    school_address NVARCHAR(255),
    state NVARCHAR(150),
    district NVARCHAR(100),
    start_date datetime
)
AS
BEGIN
    DECLARE @tbl_exists BIT;

    SET @tbl_exists = ISNULL((SELECT 1 FROM INFORMATION_SCHEMA.TABLES 
                              WHERE Table_Name LIKE '%School'),0)

    IF @tbl_exists = 1      
    BEGIN
        SELECT 
            university_id, school_number, school_name, 
            school_address, school_state, district, school_started_date 
        FROM 
            [dbo].[tbl_school_info] 
        WHERE 
            id = @univ_id
    END
    ELSE
    BEGIN
        ---- My condition if school_ingo table does not exists 
        ---- will be querying another table.
    END

    RETURN;
END;
GO

The above is throwing the error

Msg 444, Level 16, State 2, Procedure udf_site_information, Line 24 [Batch Start Line 15] Select statements included within a function cannot return data to a client.


Solution

  • You don't receive your result, apparently. That's because you don't insert your dataset in the result table:

    insert into @returntable
    SELECT university_id,...
    

    Add this and it should work. And change this existence check as well because everyone thinks that the problem is there:)

    You should be able to simply use this form

    IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Feeds]') AND type in (N'U'))
      --abc
    ELSE
      -- xyz
    

    The same with the information_schema:

    IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES where TABLE_NAME like 'feeds')
    BEGIN
     print 'exists'
    END