SQL Server PRINT SELECT (Print a select query result)?

前端 未结 10 1629
心在旅途
心在旅途 2020-12-25 09:37

I am trying to print a selected value, is this possible?

Example:

PRINT 
    SELECT SUM(Amount) FROM Expense
相关标签:
10条回答
  • 2020-12-25 10:10

    You know, there might be an easier way but the first thing that pops to mind is:

    Declare @SumVal int;
    Select @SumVal=Sum(Amount) From Expense;
    Print @SumVal;
    

    You can, of course, print any number of fields from the table in this way. Of course, if you want to print all of the results from a query that returns multiple rows, you'd just direct your output appropriately (e.g. to Text).

    0 讨论(0)
  • 2020-12-25 10:11

    If you're OK with viewing it as XML:

    DECLARE @xmltmp xml = (SELECT * FROM table FOR XML AUTO)
    PRINT CONVERT(NVARCHAR(MAX), @xmltmp)
    

    While the OP's question as asked doesn't necessarily require this, it's useful if you got here looking to print multiple rows/columns (within reason).

    0 讨论(0)
  • 2020-12-25 10:16

    If you want to print multiple rows, you can iterate through the result by using a cursor. e.g. print all names from sys.database_principals

    DECLARE @name nvarchar(128)
    
    DECLARE cur CURSOR FOR
    SELECT name FROM sys.database_principals
    
    OPEN cur
    
    FETCH NEXT FROM cur INTO @name;
    WHILE @@FETCH_STATUS = 0
    BEGIN   
    PRINT @name
    FETCH NEXT FROM cur INTO @name;
    END
    
    CLOSE cur;
    DEALLOCATE cur;
    
    0 讨论(0)
  • 2020-12-25 10:16

    If you want to print more than a single result, just select rows into a temporary table, then select from that temp table into a buffer, then print the buffer:

    drop table if exists #temp
    
    -- we just want to see our rows, not how many were inserted
    set nocount on
    
    select * into #temp from MyTable
    
    -- note: SSMS will only show 8000 chars
    declare @buffer varchar(MAX) = ''
    
    select @buffer = @buffer + Col1 + ' ' + Col2 + CHAR(10) from #temp
    
    print @buffer
    
    
    0 讨论(0)
提交回复
热议问题