Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dump a SELECT statement to the "Messages" pane in SQL Server mgmt studio from a stored procedure?

I can use the PRINT statement in a stored procedure to debug my code. I see the output in the Messages tab of SQL Server Management Studio. How can I dump one or more entire SELECT statement outputs to that Messages tab?

My stored procedure returns several output variables so returning a single dataset isn't an option here. I am struggling with finding a good way to debug my complex procedures.

like image 342
srmark Avatar asked Jul 02 '09 19:07

srmark


People also ask

How do I print a select statement from a stored procedure in SQL Server?

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

Can we write select statement in stored procedure?

We can not directly use stored procedures in a SELECT statement.

How will you store select query result in variable in SQL Server?

This provides a way to save a result returned from one query, then refer to it later in other queries. The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving.


2 Answers

Set the "Results to Text" option and your Results and Messages tabs will be consolidated to a single tab, combining your PRINT and SELECT statements.

To set Results to Text, either:

  • Control-T
  • Query menu \ Results To \ Results to Text
like image 170
boflynn Avatar answered Nov 15 '22 11:11

boflynn


Getting the entire contents of a query to print to the messages window would probably be more trouble than it's worth. Instead, I would recommend debugging the procedure from a query window. What you can do is add an optional parameter to your procedure, with a default of NULL. Your app won't be passing it, so you can use this to your advantage. Ex:

Alter Procedure Foo(@Col1 int, @col2 varchar(20), @Debug Bit = NULL)
As
SET NOCOUNT ON

If @Debug = 1
  Begin
    Select * From SomeTable Where Col1 = @Col1
  End

-- The rest of your code here

Then, when you call this procedure from a query window, simply pass in a value of 1 to the procedure for that @Debug parameter

like image 29
George Mastros Avatar answered Nov 15 '22 12:11

George Mastros