SSMS: Separating blocks of comments while collapsed - formatting

Is there a way in SSMS editor to visually separate two comment blocks that are placed one right after another when the comments are collapsed?
Please look at the link below - remember that this code is just for demonstration purpose.
When this code is collapsed in the SSMS editor, I see all the commented code collapsed.
I want to be able to see each comment block as a separate collapsed region, as in below (this is an edited image) -
I did consider using a GO, but in my case this code is part of a stored procedure, and I have a BEGIN and END that encapsulates this part of code, so that will not work.
I thought of using BEGIN/END, but that will not work either because I only have comments and no code that goes inside.
The closest work-around I came up with is using a blank PRINT '' - but, I fee this is redundant, and even counter-productive when used inside a stored procedure that will always be called from the application and would never be run from SSMS except when debugging.
Does anyone have any ideas on this? Suggestions/direction of any free third-party plug-ins is also appreciated.

I don't know of any way to do it without the comments collapsing into one region.
In SQL Server 2008 Management Studio (and probably most recent ones), you can use {$REGION} to at least give you a way to name or describe the collapsed region, which may help:
{$REGION "Comment One"}
-- This is comment one
{$ENDREGION}
SELECT dbo.
{$REGION "This is comment two"}
-- This is a separate comment
{$ENDREGION}
SELECT ...
But there has to be content between the two regions, or they still get merged into one.
The above also works while embedded inside /*..*/ comments, too (which is valid T-SQL, for #scriptfromscratch), but it still merges the comments unless there is content between them:
/* {$REGION "Test region 1"}
-- This is a test comment
{$ENDREGION}
*/
SELECT dbo.something
/* {$REGION "Test region 2"}
This is test comment 2
{$ENDREGION}
*/
SELECT dbo.
It looks to me like you'll need a third-party tool of some sort that provides this functionality, but I'm not aware of one that does this, I'm afraid.

I know this is an old thread, but as I don't see the simple solution I use, I thought I'd chime in.
I tend to use block comments mostly, and inline comments where there's only going to be one line or something short. If your closing block comment tag is followed by a semicolon, you can collapse any adjacent blocks independently, as shown below.
FYI this works in SSMS 2012, I can't vouch for any other version.
Unfortunately this cannot work for adjacent inline comments. The OP would probably be better off using a block comment to enclose any adjacent/related comments into separate blocks instead.
Ken White is on the right track, however the $REGION stuff is unnecessary in my opinion. The following approach achieves the exact same effect, except much more cleanly.
Using $REGION to group commands would be equally clumsy, as flagrant use of BEGIN END blocks will do the same job. Just remember to indent properly to avoid confusion.
Enjoy

Related

Looking for an explanation of this attempted SQL injection query

Looking through my logs I found the following query string as an attempt to perform a SQL injection, probably from an automated tool:
(select*from(select+sleep(10)union/**/select+1)a)
From what I can tell, it’s attempting a timing based attack to see if any of the tables in my database start with “a” - the sleep function will only run if the union query matches something? But I am a bit confused about other parts of the attack:
Why are there plus signs between parts of the query?
Why is there a comment as part of the query string?
Would be interested in any answers - I’m fairly certain my site hasn’t been compromised as I haven’t scanned further activity on that query and can’t get it to execute myself, so just wondering if my intuition was correct. Cheers!
I don't know what the point of this is, nor what the point is of trying to figure out the point. Injections are easier to block than to reverse engineer, and the latter doesn't contribute much to the former.
The point of the + and the /**/ are probably pretty much the same, they separate tokens without the use of whitespace. Presumably someone thinks whitespace is going to trigger some kind of alarm or blockage.
The 'a' is just an alias, and is probably there to avoid the error 'ERROR: subquery in FROM must have an alias'
This won't work in stock PostgreSQL because there is no function spelled sleep. They might be targeting a different DBMS, or maybe PostgreSQL with a specific app/framework in use which creates its own sleep function.
The sleep is probably there in case the system doesn't return meaningful messages to the end user. If it takes 10 seconds to get a response, then you know the sleep got executed. If it immediately returns, you know it didn't execute, but don't know why it didn't.
This is meant to detect a SQL injection (probably through an HTML parameter) via a timing attack. The inserted comments (as other people have mentioned) are meant to remove whitespace while still allowing the query to parse in an attempt to fool custom (badly designed) sanitization. The "+" is likely meant to be decoded into a space after passing through HTML decoding.
If you replace the whitespace and add indentation it's easier to see what's going on:
select * <-- match any number of columns on the original query
from
(select <-- nested sub-query in the from clause
sleep(10) <-- timing attack meant to detect whether the SQL ran
union <-- not sure why the union is needed
select 1) a <-- alias the subquery to "a"
) <-- close off matching parens in injected SQL?
I don't think this is attempting to look for tables that start with a, simply run a sleep on a possible recursive query, which could cause your database trouble, if a bunch of them execute.
The + signs are likely an attempt to do some string concatenation... That would be my guess
Regardless I would strongly look at tracing back where this originated from and sanitizing your inputs on your site so raw inputs ( potential sql ) is not being dropped into queries.

Why does this choose statement not work in an Access criteria?

I really don't know what I did wrong...I was following advice from a blog post stating that this code would allow me to keep Access from breaking up my criteria (I have a ton of criteria and it was making this statement into four separate lines and adding columns.) Here's my code right now.
Choose(1,(([dbo_customerQuery].[store])>=[forms]![TransactionsForm]![txtStoreFrom] Or
[forms]![TransactionsForm]![txtStoreFrom] Is Null) And (([dbo_customerQuery].[store])
<=[forms]![TransactionsForm]![txtStoreTo] Or [forms]![TransactionsForm]![txtStoreTo]
Is Null))
The statement inside of the choose is definitely correct so am I using "Choose" wrong? I don't get it, the blog post used it exactly this way. When I execute queries, no matter what those fields do, I end up getting no results. The query is supposed to filter based on a date range, taking null values into account
My concern is that you are trying to work around a bad design. You may get this immediate issue solved to some degree, and continue to build the bad design. Access is flexible, and forgiving, but there's a big price eventually -- maybe you're already there.
I realize this is not an answer. It may seem rude -- I apologize. But I think the general advice may help you. I'll tag this "community wiki" since I'm not contributing to a programming solution.
It might be the placing of the parens, try this:
Choose(1,(([dbo_customerQuery].[store]>=[forms]![TransactionsForm]![txtStoreFrom]) Or
[forms]![TransactionsForm]![txtStoreFrom] Is Null) And (([dbo_customerQuery].[store]
<=[forms]![TransactionsForm]![txtStoreTo]) Or [forms]![TransactionsForm]![txtStoreTo]
Is Null))
I have moved two closing parentheses.
I have found what it was now. My statement
Choose(1,(([dbo_customerQuery].[store])>=[forms]![TransactionsForm]![txtStoreFrom] Or
[forms]![TransactionsForm]![txtStoreFrom] Is Null) And (([dbo_customerQuery].[store])
<=[forms]![TransactionsForm]![txtStoreTo] Or [forms]![TransactionsForm]![txtStoreTo]
Is Null))
was correct, the problem was I assumed it would work as a criteria, but it actually had to be done exactly as in the blog post posted above. It had to be posted directly as the FIELD, with "<> False" being the criteria.
Once done, it did stay on one line, and it worked just as expected.

how to update field names automatically after updating SQL

I am changing the command text for a data set inside the .rdl ffile:
I would like to know how can I update the resulting fields that are returned by the select statement:
I know that these fields must be automatically generated, so I was wondering if it's possible to update them right after editing the SQL code inline??
Usually when someone wants to have a look at the data in command text they are wanting it for reference to an end user(from what I have seen). You may want to amend it but ultimately with reporting your first goal should be: "What am I doing this for?" If your goal is dynamic creation at runtime then I would avoid this and offer a few other suggestions:
Procertize it. Making a stored procedure if you have the know how in SQL Server is a convenient and fast way to get what you want and you can optimize it if you know what you are doing with your SQL FU to get good results. The downside would be if you work with multiple environments you have to deploy your code for the TSQL as well as the RDL file.
Use an expression to build the dataset at runtime. In cases where I have been told that the query itself was not properly optimized by other developers they have mentioned doing this. I myself do not always see the advantage of doing this versus just having your predicate construction work well with good indexing on the source engine. Regardless you can build your dataset at runtime. It would be similar to hitting 'fx' next to the text and then putting in something like this(assuming you have a variable named #Start):
="Select thing
from table
Where >= " & Parameters!Start.Value
Again I have not really seen if this is really that much faster than:
Select thing
from table
Where >= #Start
But it is there if you just want to build it dynamically.
You can try to build your expression dynamically from parameters being PART of the select statement. SSRS is all about the 'expressions' and what you can do with them. Once you jump in and learn how they apply to everything you can go nuts so to speak on using them. A general rule though is the more of them you use and rely on the slower your reports will become.
I hope some of this may help, I would ask first is something dynamic due to a need to be event driven or is performance related.

getting back carriage returns after using mysql_real_escape_string()

I'm finishing up on my website and want to make it very sql injection safe. A major part of that is going through and using mysql_real_escape_string() on any potential user input.
This is fine for most things, where I simply need to use 'stripslashes' to return the original content to show on the page. However, I cannot seem to get carriage returns back.
There are several places where users might submit pieces with carriage returns (messages are one example, starting with eg, 'Hi John,' then returning twice to the main message). How Can I fix this? Stripslashes just returns the message with rnrn, which is no good.
As an example (of me trying to test all possible inputs).
This text:
Once upon a time there was a guy named "steve" or 'john' or backslash (\)
Then, two lines later, he left.
Is saved like this in the SQL database:
Once upon a time there was a guy named \"steve\" or \'john\' or backslash (\\)\r\n\r\nThen, two lines later, he left.
And using stripslashes leaves it like this (note I am doing the following to print it to the html - :
Once upon a time there was a guy named "steve" or 'john' or backslash (\)rnrnThen, two lines later, he left.
I've tried nl2br, but for some reason it doesn't do anything. Would love any thoughts here, thanks so much!
There are a lot of things messed up.
mysql_real_escape_string() has nothing to do neither with sql injections nor with user input.
there shouldn't be unconditional stripslashes, but on purpose only.
When properly used, escaping is not going to database. NO ever need for stripslashes on retrieve.
if you have slashes in the database, you have excessive escaping. either yourcode adds slashes twice, or you're using placeholders which makes escaping useless

Can I write SQL using speech recognition?

I have wrist pain when I type and I would like to start writing SQL statements, stored procedure, and views using speech recognition.
Yes. SQL is well-suited to speech recognition (as well-suited as a programming language can be, that is), given it's limited vocabulary and sentence-like structure. Aside from formatting the SQL so that it looks nice, I can dictate it much faster than typing. Dictating code isn't for everyone, however. It can be quite frustrating in the beginning. The people who try this and stick with it will probably be those who have no other choice.
I use Dragon NaturallySpeaking 10 Professional. The Professional version has the tools that are needed to create a custom vocabulary like this. Version 9 should work fine, also. It's expensive, so try to get the company you work for to pay for it if possible. Get a decent headset microphone also. The one that comes with NaturallySpeaking isn't good enough (but you may want to try it first to see if it works for you). KnowBrainer is a good place for microphone recommendations.
2009-01-05 Update: I have added tips below specific to dictating in SQL Server Management Studio.
2012-01-04 Update: I have been keeping track of Microsoft's WSR for quite a while now, hoping tools would be added to easily create a completely custom vocabulary from scratch like I am doing in this tutorial with NaturallySpeaking. Unfortunately, it appears that this can only be done through the API (SAPI). I don't have the time to write that code, so I will continue to use NaturallySpeaking to write code until something better comes along.
Preparation
Clean up your database names and code
Dictating "SELECT PT_17, PT_28, PT_29 FROM HIK.dbo.PATINFO" would be a pain in the butt, but I guess it would be possible. You would have to set a lot of pronunciations, since NaturallySpeaking would have no idea how "PT_17" would sound. This would be preferable for dictation:
SELECT Patient.FirstName, Patient.MiddleName, Patient.LastName FROM Claim.dbo.Patient AS Patient WHERE Patient.LastName LIKE '%smith%'
I switched to my TSQL vocabulary to dictate the above statement. Everything up to the LIKE statement is spoken just as it appears. '%smith%' was dictated as "open-single-quote percent-sign sierra mike india tango hotel percent-sign close-single-quote [PAUSE] compound-that". Using consistent table aliases and always preceding fields with them helps improve accuracy, since NaturallySpeaking keeps statistics of how often one word appears near another.
Create a word list of SQL keywords
Put one word on each line. You can optionally follow a word with a backslash (\) and a pronunciation. NaturallySpeaking uses a small backup dictionary of words to determine the pronunciation of words you add to a vocabulary, so it has no problem figuring out how SELECT, FROM, and WHERE are pronounced. It can sometimes figure out a compound word, and it makes its best guess for something like XACT_ABORT. I would provide pronunciations for cases like these. The database you use will determine what words the list contains - check your documentation for a list of keywords. Your list will look something like this, but be much longer.
SELECT
WHERE
FROM
XACT_ABORT\exact-abort
MAXDOP
NOLOCK\no-lock
LEN
RETURNS
CURSOR
MONEY
Also add these words
\New-Line
\New-Paragraph
\All-Caps
\All-Caps-On
\All-Caps-Off
\Cap
\Caps-On
\Caps-Off
\No-Caps
\No-Caps-On
\No-Caps-Off
\No-Space
\No-Space-On
\No-Space-Off
\space-bar
\tab-key
a\alpha
b\bravo
c\charlie
d\delta
e\echo
f\foxtrot
g\golf
h\hotel
i\india
j\juliet
k\kilo
l\lima
m\mike
n\november
o\oscar
p\papa
q\quebec
r\romeo
s\sierra
t\tango
u\uniform
v\victor
w\whiskey
x\xray
y\yankee
z\zulu
PM
AM
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
nineteen
twenty
thirty
fourty
fifty
sixty
seventy
eighty
ninety
hundred
thousand
million
billion
trillion
Keep this list around, since you'll probably modify it several times and re-create your vocabulary to get it the way you like it.
Create a word list of your database object names
This is how I do it in SQL Server:
SELECT DISTINCT * FROM
(
SELECT DISTINCT [name] FROM Database1.[dbo].[sysobjects] WHERE xtype not IN ('F', 'S', 'PK', 'D', 'UQ')
UNION
SELECT DISTINCT column_name AS [name] FROM Database1.information_schema.[columns]
UNION
SELECT DISTINCT [name] FROM Database2.[dbo].[sysobjects] WHERE xtype not IN ('F', 'S', 'PK', 'D', 'UQ')
UNION
SELECT DISTINCT column_name AS [name] FROM Database2.information_schema.[columns]
...
) AS UnionTable
Copy and paste the results into a text file.
Create pronunciations for your database object names
Use the same format for pronunciations as listed above. An easy way to create these is to use a regex search and replace function. In SQL Server Management Studio or Visual Studio the following (non-standard) regex will create pronunciations for two word mixed case names.
Find: ^{[A-Z][a-z]+}{[A-Z][a-z]+}$
Replace: \0\\\1-\2
Review the pronunciations and clean up anything that doesn't look right. For acronyms, ASP becomes `A.S.P.'. Keep this list around, as well. If you decide to make vocabularies for other programming languages, you will probably include these words if you're a database developer.
Create a text document that contains all of your SQL code (views, procedures, etc.)
SQL Server:
SELECT * FROM Database1.dbo.[View] UNION SELECT * FROM Database1.dbo.Routine UNION
SELECT * FROM Database2.dbo.[View] UNION SELECT * FROM Database2.dbo.Routine
...
ORDER BY [Name]
Remove comments and literal strings. Regex search and replace works well for this.
Build your vocabulary
Install NaturallySpeaking and create a new user if you have not already.
Create a new vocabulary
Click on "NaturallySpeaking | Manage Vocabularies...". Click New. Name the vocabulary something appropriate, such as "SQL". Base it on "Base General - Empty Dictation". When it asks you if you want to scan your email or documents, click cancel.
Import words
Click "Words | Import". Add the two word lists you created and import them.
Adapt to writing style
Click "Tools | Accuracy Center". Click "Add words from your documents to the vocabulary". Use the default settings, and select the document you created which contains your code.
Try dictating some SQL
The first thing you'll probably want to dictate is a select statement. Keep in mind that SELECT is what you use to begin a command in NaturallySpeaking that selects text. Because of this, you'll want to say "Cap" before dictating it so NaturallySpeaking doesn't get confused. That's it. Well, at least enough to get you started. Modify your word lists, pronunciations, and word properties as needed. There are other things you can do to increase accuracy and the speed at which you can dictate. As I think of them, I will edit this post and add them here.
Tips for dictating into SQL Server Management Studio
If you dictate into SQL Server Management Studio, you may notice very slow performance. Try the following to alleviate this:
Turn off all toolbars (create macros
to access commonly used
functionality)
Keep as few panes and
documents open as possible
Keep only one database open at a time
Hide search results after you're done
with them (Ctrl+R)
If all else
fails, close and reopen management
studio
Display the tab stops in the edit window to make it easier to format your SQL.
Query Analyzer from SQL Server 2000 does not have these issues.
http://voicecode.io
I recently released VoiceCode, a coding-by-voice solution I created to solve my own RSI issues.
I use it for coding in Sublime Text and Xcode, as well as general computer usage. It works for writing code in any language including SQL. The great thing about this solution is that all the commands can be chained into "command phrases" so you don't have to pause between every individual command like you do with other voice command solutions.
It has builtin support for all standard variable-name formats (snake case, camel case, etc), has builtin commands for every permutation of keyboard shortcuts (ie command-shift-5, command-option-shift-T, and so on), has cursor movement commands, app switching commands, window switching commands, commands for symbol combos like "=>", "||", ">=", etc, and tons more. Plus it is very easy to add your own custom commands as well.