SQL server stored procedure return a table

后端 未结 9 2209
情书的邮戳
情书的邮戳 2020-12-04 19:39

I have a stored procedure that takes in two parameters. I can execute it successfully in Server Management Studio. It shows me the results which are as I expect. However it

9条回答
  •  温柔的废话
    2020-12-04 20:28

    Consider creating a function which can return a table and be used in a query.

    https://msdn.microsoft.com/en-us/library/ms186755.aspx

    The main difference between a function and a procedure is that a function makes no changes to any table. It only returns a value.

    In this example I'm creating a query to give me the counts of all the columns in a given table which aren't null or empty.

    There are probably many ways to clean this up. But it illustrates a function well.

    USE Northwind
    
    CREATE FUNCTION usp_listFields(@schema VARCHAR(50), @table VARCHAR(50))
    RETURNS @query TABLE (
        FieldName VARCHAR(255)
        )
    BEGIN
        INSERT @query
        SELECT
            'SELECT ''' + @table+'~'+RTRIM(COLUMN_NAME)+'~''+CONVERT(VARCHAR, COUNT(*)) '+
        'FROM '+@schema+'.'+@table+' '+
              ' WHERE isnull("'+RTRIM(COLUMN_NAME)+'",'''')<>'''' UNION'
        FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table and TABLE_SCHEMA = @schema
        RETURN
    END
    

    Then executing the function with

    SELECT * FROM usp_listFields('Employees')
    

    produces a number of rows like:

    SELECT 'Employees~EmployeeID~'+CONVERT(VARCHAR, COUNT(*)) FROM dbo.Employees  WHERE isnull("EmployeeID",'')<>'' UNION
    SELECT 'Employees~LastName~'+CONVERT(VARCHAR, COUNT(*)) FROM dbo.Employees  WHERE isnull("LastName",'')<>'' UNION
    SELECT 'Employees~FirstName~'+CONVERT(VARCHAR, COUNT(*)) FROM dbo.Employees  WHERE isnull("FirstName",'')<>'' UNION
    

提交回复
热议问题