Microsoft SQL Server 2005 Console Write Line - sql-server

Is there a way to write a message to the console? I'd like to write some debug data if it's possible.

The PRINT command emits a message that may be shown in a console depending on what tool you're using:
PRINT 'Hello, world!'
Not all clients necessarily show these messages though.

You mean PRINT?
For example:
PRINT 'hello world'

For long-running operations, instead of PRINT, you might need to use the RAISERROR with NOWAIT option workaround, since the messages display is cached.

Higher overhead but you can log to the event logging system with xp_logevent.

Related

Avoid newline when using raiserror

Suppose I debug using raiserror, like so:
raiserror('Trying to do something...',0,0) with nowait
(queries that do something)
raiserror('Done.',0,0) with nowait
It would be handy to have this output in the "Messages" of SSMS in a single line:
Trying to do something...Done.
Is there a way? I haven't found anything around
No, either you wait until both actions are complete and print a single line with one call, or you have the output on two lines. SSMS (and ADS) just aren’t equipped to do what you want to do.

SQL Server - Display only the most recent print statement in SSMS messages pane (while loop)

I have a script that usually takes several hours to run (mostly because it needs to be looped through a few hundred thousand times. Currently I have a print statement to check the progress so that each time it completes 1 iteration it prints out : "Query 1 of 100000 complete" then below that "Query 2 of 100000 complete" and so on and so forth.
Is there any way to delete old messages in SQL Server Management Studio so that the messages pane only displays the most recent print statement?
You can't clear the print messages in SSMS. Print may not print immediately if you don't have GO statement in your queries. PRINT doesn’t necessarily output anything at the moment it’s called.
You should not use print for tracking the progress of your query. To know more about this read Stop Using PRINT to Track Query Progress
If you want to track the progress immediately, instead of print you can use RAISEERROR like following.
RAISERROR('SOME MESSAGE YOU WANT TO SHOW', 0, 1) WITH NOWAIT;
Ideally, you should have a log table, where you should be entering the progress for each step. This will give you the correct picture of what is going on.
Instead of using SSMS, you could use sqlcmd instead and store the output to a text file. For example, in powershell, you could run a command like:
sqlcmd -S YourServer -d YourDatabase -Q "EXEC YourStoredProcedure" > "C:\temp\sqlcmdsp.log"
Then, if you want to see where the process is at, you could simply open the txt if a non-locking application (like notepad or notepad++) and see where it's got to.

sql print statements from pyodbc

How do I get the output from the sql_query?
import pyodbc
sql_query = "print 'Hello World'"
conn = pyodbc.connect("DRIVER={SQL Server};
SERVER=myserver;
DATABASE=mydatabase;
UID=myusername;
PWD=mypassword")
cur = conn.cursor()
cur.execute(sql_query)
cur.commit()
for row in cursor.fetchall():
print row
So far I think an SQL print is out of band from the usual structured responses?
http://www.easysoft.com/developer/languages/perl/sql_server_unix_tutorial.html#print_statement_status_messages has something similar to what I'm trying to do in Perl.
The closest I can see is the optional:
http://www.python.org/dev/peps/pep-0249/#cursor-messages So I guess it's just not implemented?
When running the query PRINT 'Hello World' the output is being returned as console output (string), and fetchall is reviewing the result set (object) from a query. RAISERROR is an error condition, and can stop the process. I'm not saying this isn't a solution, but maybe you just want to print some feedback without creating an error condition.
I think you can achieve the result you are looking for by changing
[PRINT 'Hello World'] to [SELECT 'Hello World']
I think this will create a single row of data in a result set with the text you wanted in it, that should show up in fetchall, and see if you get the results you are expecting.
Hope that helps provide an alternative you can try!
Use RAISERROR over PRINT. Use it with NOWAIT to get output immediately. I don't know how to handle this in python, but in ADO.NET you can use the InfoMessage event on SqlConnection. Maybe there is something similar in Python.

How do I exploit "EXEC #sql"?

My co-worker is being unsafe with his code and is allowing a user to upload an SQL file to be run on the server.
He strips out any key words in the file such as "EXEC", "DROP", "UPDATE", "INSERT", "TRUNC"
I want to show him the error of his ways by exploiting his EXEC ( #sql )
My first attempt will be with 'EXEXECEC (N''SELECT ''You DRDROPOPped the ball Bob!'')'
But he might filter that all out in a loop.
Is there a way I can exploit my co-worker's code? Or is filtering out the key words enough?
Edit: I got him to check in his code. If the code contains a keyword he does not execute it. I'm still trying to figure out how to exploit this using the binary conversion.
Tell your co-worker he's a moron.
Do an obfuscated SQL query, something like:
select #sql = 0x44524f5020426f627350616e7473
This will need some tweaking depending on what the rest of the code looks like, but the idea is to encode your code in hex and execute it (or rather, let it be executed). There are other ways to obfuscate code to be injected.
You've got a huge security hole there. And the funny part is, this is not even something that needs to be reinvented. The proper way to stop such things from happening is to create and use an account with the correct permissions (eg: can only perform select queries on tables x, y and z).
Have a look at ASCII Encoded/Binary attacks ...
should convince your friend he is doomed.. ;)
And here some help on how to encode the strings ..
Converting a String to HEX in SQL

PRINT statement in T-SQL

Why does the PRINT statement in T-SQL seem to only sometimes work? What are the constraints on using it? It seems sometimes if a result set is generated, it becomes a null function, I assumed to prevent corrupting the resultset, but could it's output not go out in another result set, such as the row count?
So, if you have a statement something like the following, you're saying that you get no 'print' result?
select * from sysobjects
PRINT 'Just selected * from sysobjects'
If you're using SQL Query Analyzer, you'll see that there are two tabs down at the bottom, one of which is "Messages" and that's where the 'print' statements will show up.
If you're concerned about the timing of seeing the print statements, you may want to try using something like
raiserror ('My Print Statement', 10,1) with nowait
This will give you the message immediately as the statement is reached, rather than buffering the output, as the Query Analyzer will do under most conditions.
The Print statement in TSQL is a misunderstood creature, probably because of its name. It actually sends a message to the error/message-handling mechanism that then transfers it to the calling application. PRINT is pretty dumb. You can only send 8000 characters (4000 unicode chars). You can send a literal string, a string variable (varchar or char) or a string expression. If you use RAISERROR, then you are limited to a string of just 2,044 characters. However, it is much easier to use it to send information to the calling application since it calls a formatting function similar to the old printf in the standard C library. RAISERROR can also specify an error number, a severity, and a state code in addition to the text message, and it can also be used to return user-defined messages created using the sp_addmessage system stored procedure. You can also force the messages to be logged.
Your error-handling routines won’t be any good for receiving messages, despite messages and errors being so similar. The technique varies, of course, according to the actual way you connect to the database (OLBC, OLEDB etc). In order to receive and deal with messages from the SQL Server Database Engine, when you’re using System.Data.SQLClient, you’ll need to create a SqlInfoMessageEventHandler delegate, identifying the method that handles the event, to listen for the InfoMessage event on the SqlConnection class. You’ll find that message-context information such as severity and state are passed as arguments to the callback, because from the system perspective, these messages are just like errors.
It is always a good idea to have a way of getting these messages in your application, even if you are just spooling to a file, because there is always going to be a use for them when you are trying to chase a really obscure problem. However, I can’t think I’d want the end users to ever see them unless you can reserve an informational level that displays stuff in the application.
Query Analyzer buffers messages. The PRINT and RAISERROR statements both use this buffer, but the RAISERROR statement has a WITH NOWAIT option. To print a message immediately use the following:
RAISERROR ('Your message', 0, 1) WITH NOWAIT
RAISERROR will only display 400 characters of your message and uses a syntax similar to the C printf function for formatting text.
Please note that the use of RAISERROR with the WITH NOWAIT option will flush the message buffer, so all previously buffered information will be output also.
I recently ran into this, and it ended up being because I had a convert statement on a null variable. Since that was causing errors, the entire print statement was rendering as null, and not printing at all.
Example - This will fail:
declare #myID int=null
print 'First Statement: ' + convert(varchar(4), #myID)
Example - This will print:
declare #myID int=null
print 'Second Statement: ' + coalesce(Convert(varchar(4), #myID),'#myID is null')
For the benefit of anyone else reading this question that really is missing print statements from their output, there actually are cases where the print executes but is not returned to the client. I can't tell you specifically what they are. I can tell you that if you put a go statement immediately before and after any print statement, you will see if it is executed.
Do you have variables that are associated with these print statements been output? if so, I have found that if the variable has no value then the print statement will not be ouput.

Resources