Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to echo print statements while executing a sql script

Tags:

sql

mysql

We have a simple sql script which needs to be executed against a MySQL database and we would like print log statements on the progress of the script (e.g. Inserted 10 records into foo or Deleted 5 records from bar). How do we do this?

  1. I would like to know the syntax to be used for insert/update/delete statements.
  2. How do I know about the number of rows affected by my statement(s).
  3. I would also like to control printing them using a ECHO off or on command at the top of the script.
  4. The script should be portable across Windows / Linux OS.
like image 777
Joe Avatar asked Nov 16 '11 06:11

Joe


People also ask

Can you echo in SQL?

The ECHO setting tells SQL*Plus whether you want the contents of script files to be echoed to the screen as they are executed.

How do I print a SQL output statement?

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

How do you display text in SQL?

:Explanation: Note: You can use literal string (enclosed in single or double quotation mark) just like we use a column name in the SELECT statement. If you use the literal string with a column then it will be displayed in every row of the query results.


2 Answers

This will give you are simple print within a sql script:

select 'This is a comment' AS ''; 

Alternatively, this will add some dynamic data to your status update if used directly after an update, delete, or insert command:

select concat ("Updated ", row_count(), " rows") as '';  
like image 124
blankabout Avatar answered Sep 28 '22 06:09

blankabout


I don't know if this helps:

suppose you want to run a sql script (test.sql) from the command line:

mysql < test.sql 

and the contents of test.sql is something like:

SELECT * FROM information_schema.SCHEMATA; \! echo "I like to party..."; 

The console will show something like:

CATALOG_NAME    SCHEMA_NAME            DEFAULT_CHARACTER_SET_NAME                def    information_schema     utf8          def    mysql                  utf8          def    performance_schema     utf8          def    sys                    utf8 I like to party... 

So you can execute terminal commands inside an sql statement by just using \!, provided the script is run via a command line.

\! #terminal_commands 
like image 28
Craig Wayne Avatar answered Sep 28 '22 06:09

Craig Wayne