sql server select from case db [duplicate] - sql

This question already has answers here:
How to use a variable for the database name in T-SQL?
(4 answers)
Closed 8 years ago.
I have 2 db on one server.
I need to write procedure that does select basing on #db variable.
I know 2 possibilities for this:
I declare #SQL nvarchar(max) and generating my query in plain text. Then i do exec #SQL.
Bad variant imho.
I do 2 similar queries and use if #db='' 1st query else 2nd query. Another bad variant because it is code duplicate.
Question is - is there any way to do like this or similar: select * from #db.dbo.table?

Using "exec #SQL" isn't evil. If it gets the job done and you're not exposing yourself to any security risks then it may be the best way to go. Another option would be to consider using a real programming language like c# (or whatever your preference is) since they are better equipped to handle these sort of dynamic requirements.

Related

Declaring variables for Oracle SQL in dbVisualizer

Using an Oracle database (currently 18g) through dbVisualizer, I have SQL that has parameters peppered throughout. Some of the parameters are in multiple places. The query I'm working with right now has 13 distinct parameter names with 56 total references in the code. I have some standard values I use for testing. I don't want to use the interface dbVisualizer presents for entering them manually. I want to use a text editor to enter my test values and put them all at the beginning of my code so I don't risk fat-fingering my SQL logic and so I can delete or comment out that section when I'm done testing.
I've done this for decades in SQL Server...
declare #varname varchar(50)
set #varname = 'asdf'
select #varname
...but I don't see a way to do this in Oracle. I have read many posts regarding how to do this using PL/SQL or SQL*Plus (like https://dba.stackexchange.com/questions/3652/how-do-i-declare-and-use-variables-in-oracle) that don't work for my environment. I have also seen posts with accepted answers that just don't work (like Declare a variable in Oracle SQL to use in a query).
How can I declare variables in Oracle SQL through dbVisualizer as easily as I can in SQL Server using SSMS?
I have needed this functionality for about 3 years now. Since I finally found enough information to figure it out, and since I've never found this info on StackExchange, I'm asking and answering my own question in the hopes that others don't suffer needlessly as long as I have.
I found a post (https://support.dbvis.com/support/discussions/topics/1000076719) describing how to do this, but it looks like some of the post got lost in a forum upgrade. Fiddling around a bit I found that this will work:
#echo ${ MY_VARCHAR1 ||My Value|| String }$
#echo ${ MY_VARCHAR2 || My Other Value || String }$
#echo ${ MY_INTEGER || 13467 || Integer }$
#echo ${ MY_DATE || 1983-08-25 || Date }$
;
SELECT ${MY_VARCHAR1}$ "VarcharVal"
, REPLACE(${MY_VARCHAR2}$, ' ', '[SPACE]') "VarcharValWithLeadingAndTrailingSpaces"
, ${MY_INTEGER}$ "IntegerVal"
, ${MY_DATE}$ "DateVal"
FROM DUAL
;
Notice the results for MY_VARCHAR2. While integers and dates are handled cleanly, you want to be sure to not have spaces around the value for string data.
Update: Adjusted code per dbVisualizer docs. Same result, though.

How to run Regex in MSaccess (If supported)? [duplicate]

This question already has answers here:
Regular Expressions in MS Access VBA?
(2 answers)
Closed 4 years ago.
This is my first post, please be nice.
I want to know if it is possible to run similar to an Oracle regexp_match/regexp_replace in MSaccess 2010.
The code I usually use is something like
select * from table
where regexp_match(name, '^foo$')
How do I do this in Access,
Yes I have tried google search, unfortunately I was unsuccessful.
Do I have to use VBA for it, if so how?
Thank you, much appreciated
MS Access does not have built-in regular expression support.
However, this query:
select t.*
from table t
where regexp_match(t.name, '^foo$')
Is better written as:
select t.*
from table t
where t.name = 'foo';
Equality is more efficient in any database.

what is use of question mark in sql [duplicate]

This question already has answers here:
What is the question mark's significance in MySQL at "WHERE column = ?"?
(4 answers)
What does a question mark represent in SQL queries?
(6 answers)
Closed 9 years ago.
I was just surfing the net and found a query something like:
sql = "select milk_rate from special_milk_rate
where code_producer_id=? and effective_from <= ?
and effective_till >= ?"
what exactly this query means i means what is the use of ? in this statement.
and one thing more what is use of & in sql.
This usually implies a prepared statement, where the parameters are filled in later. (see e.g. http://en.wikipedia.org/wiki/Prepared_statements#Parameterized_statements).
what exactly this query means i means what is the use of ? in this statement.
The question marks are for parameters.
and one thing more what is use of & in sql.
& is a bitwise AND operator in sql
The question marks are supposed to contain the actual parameters.
E.g.
"select milk_rate from special_milk_rate
where code_producer_id=2 and effective_from <= '20101231'
and effective_till >= '20110124'"
& usually denotes a variable or substitution value which you may be prompted for at run time
Here is nice article:
http://publib.boulder.ibm.com/infocenter/idshelp/v10/topic/com.ibm.sqls.doc/sqls610.htm#sii-02prep-18104
In some statements, parameters are
unknown when the statement is prepared
because a different value can be
inserted each time the statement is
executed. In these statements, you can
use a question-mark ( ? ) placeholder
where a parameter must be supplied
when the statement is executed.
Question marks are found in prepared statements, meaning it is parametrized and can be called again and again without having to reconstruct the whole sql statement, just by changing the parameters. Some frameworks use those that together with SqlCommands. Those encapsulate escaping and prevent sql injection attacks.
Some frameworks also allow named parameters.

Should we end the statement in T-SQL with semi-colon? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
When should I use semicolons in SQL Server?
When we are writing a SQL script in T-SQL, should we end each statement with a semi-colon? Does semi-colon work like 'GO' keyword? As of now, I see that it doesn't really matter, but I would like to know which is the best practice?
It's good to get into the habit now because CTE/WITH and MERGE need it, as well as some Service broker stuff as mentioned in the other question. Of course, you could use ;WITH cTE AS ...
C# etc monkeys have been doing it for years.
It won't work with GO because it isn't a keyword. It's a directive for SSMS and other tools to break a larger script into batches.

How do I deal with quotes ' in SQL [duplicate]

This question already has answers here:
How to anticipate and escape single quote ' in oracle
(2 answers)
Closed 7 years ago.
I have a database with names in it such as John Doe etc. Unfortunately some of these names contain quotes like Keiran O'Keefe. Now when I try and search for such names as follows:
SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe'
I (understandably) get an error.
How do I prevent this error from occurring. I am using Oracle and PLSQL.
The escape character is ', so you would need to replace the quote with two quotes.
For example,
SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe'
becomes
SELECT * FROM PEOPLE WHERE SURNAME='O''Keefe'
That said, it's probably incorrect to do this yourself. Your language may have a function to escape strings for use in SQL, but an even better option is to use parameters. Usually this works as follows.
Your SQL command would be :
SELECT * FROM PEOPLE WHERE SURNAME=?
Then, when you execute it, you pass in "O'Keefe" as a parameter.
Because the SQL is parsed before the parameter value is set, there's no way for the parameter value to alter the structure of the SQL (and it's even a little faster if you want to run the same statement several times with different parameters).
I should also point out that, while your example just causes an error, you open youself up to a lot of other problems by not escaping strings appropriately. See http://en.wikipedia.org/wiki/SQL_injection for a good starting point or the following classic xkcd comic.
Oracle 10 solution is
SELECT * FROM PEOPLE WHERE SURNAME=q'{O'Keefe}'
Parameterized queries are your friend, as suggested by Matt.
Command = SELECT * FROM PEOPLE WHERE SURNAME=?
They will protect you from headaches involved with
Strings with quotes
Querying using dates
SQL Injection
Use of parameterized SQL has other benefits, it reduces CPU overhead (as well as other resources) in Oracle by reducing the amount of work Oracle requires in order to parse the statement. If you do not use parameters (we call them bind variables in Oracle) then "select * from foo where bar='cat'" and "select * from foo where bar='dog'" are treated as separate statements, where as "select * from foo where bar=:b1" is the same statement, meaning things like syntax, validity of objects that are referenced etc...do not need to be checked again. There are occasional problems that arise when using bind variables which usually manifests itself in not getting the most efficient SQL execution plan but there are workarounds for this and these problems really depend on the predicates you are using, indexing and data skew.
Input filtering is usually done on the language level rather than database layers.
php and .NET both have their respective libraries for escaping sql statements. Check your language, see waht's available.
If your data are trustable, then you can just do a string replace to add another ' infront of the ' to escape it. Usually that is enough if there isn't any risks that the input is malicious.
I suppose a good question is what language are you using?
In PHP you would do: SELECT * FROM PEOPLE WHERE SURNAME='mysql_escape_string(O'Keefe)'
But since you didn't specify the language I will suggest that you look into a escape string function mysql or otherwise in your language.
To deal quotes if you're using Zend Framework here is the code
$db = Zend_Db_Table_Abstract::getDefaultAdapter();
$db->quoteInto('your_query_here = ?','your_value_here');
for example ;
//SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe' will become
SELECT * FROM PEOPLE WHERE SURNAME='\'O\'Keefe\''
Found in under 30s on Google...
Oracle SQL FAQ