SQL Server PRINT SELECT (Print a select query resu

2019-02-03 22:04发布

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

Example:

PRINT 
    SELECT SUM(Amount) FROM Expense

9条回答
神经病院院长
2楼-- · 2019-02-03 22:34
set @n = (select sum(Amount) from Expense)
print 'n=' + @n
查看更多
趁早两清
3楼-- · 2019-02-03 22:36

If you wish (like me) to have results containing mulitple rows of various SELECT queries "labelled" and can't manage this within the constraints of the PRINT statement in concert with the Messages tab you could turn it around and simply add messages to the Results tab per the below:

SELECT 'Results from scenario 1'
SELECT
    *
FROM tblSample

enter image description here

查看更多
SAY GOODBYE
4楼-- · 2019-02-03 22:41

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).

查看更多
老娘就宠你
5楼-- · 2019-02-03 22:45

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).

查看更多
可以哭但决不认输i
6楼-- · 2019-02-03 22:47

Add

PRINT 'Hardcoded table name -' + CAST(@@RowCount as varchar(10))

immediately after the query.

查看更多
Ridiculous、
7楼-- · 2019-02-03 22:49

You can also use the undocumented sp_MSforeachtable stored procedure as such if you are looking to do this for every table:

sp_MSforeachtable @command1 ="PRINT 'TABLE NAME: ' + '?' DECLARE @RowCount INT SET @RowCount = (SELECT COUNT(*) FROM ?) PRINT @RowCount" 
查看更多
登录 后发表回答