Keyword search to include Uniqueidentifier field - sql

I'm wanting to let a user search rows in a database by specifying a keyword to look for. There are a few fields I would like to look in for this keyword, one of which is a uniqueidentifier. The problem is, if the keyword is not a GUID, I get the following error message:
Conversion failed when converting from a character string to uniqueidentifier
The SQL I'm using to run the search looks something like this:
// do not use
string sql = #"SELECT *
FROM [MyTable]
WHERE [MyTable].[TableID] = '" + keyword + "'";
WARNING: this is just example code - DO NOT write sql commands like this as it creates a security risk
How do I write my SQL select statement such that it will not fail when keyword is not a GUID?

string sql;
Guid id;
if (Guid.TryParse(keyword, out id))
{
sql = #"SELECT *
FROM [MyTable]
WHERE [MyTable].[TableID] = '" + keyword + "'";
}
else
{
sql = //search by other way
}

Does this work for you?
string sql = #"SELECT *
FROM [MyTable]
WHERE convert(varchar,[MyTable].[TableID]) = '" + keyword + "'";

I know this doesn't really help you today, but may help future readers. In SQL Server 2012 you will be able to use TRY_CONVERT:
string sql = #"SELECT *
FROM dbo.[MyTable]
WHERE [TableID] = TRY_CONVERT(UNIQUEIDENTIFIER, '" + keyword + "');";
But what you really should be doing is passing the parameter as a strongly typed GUID, and handling the error (using try/catch) in the client program when someone enters something that isn't a GUID.

Related

how to write int value inside the query passing through asp.net

I am having the following exception when passing the query through executereader:
incorrect syntax near )"...
How do I write the 0 here?
Here's the whole query:
string query = "select distinct BillNumber,PatientName,MobileNo,DueAmount from PaymentView where RequestDate between '" + fromDate.ToString("yyyy-MM-dd") + "' and '" + toDate.ToString("yyyy-MM-dd") + "' and DueAmount>'"+value+"')";
Extra Closing bracket at end of query. Also DueAmount should not be wrap into single quotes remove it.
and DueAmount>'"+value+"')";
------------^
Note : This may lead to SQL Injection attack, My suggestion is use Sql Parameter.

double where statement in SQL and ASP

I am a little lost on how to incorporate TWO Where in my sql statement in my asp.
I am trying to get the userID and password entered previously and compare it with what I have in my database created on SQL:
I think my problem comes from my double quotation and single quotation.
UserID is a number in my database and Password is a short text.
var mycon = new ActiveXObject("ADODB.Connection");
var myrec = new ActiveXObject("ADODB.Recordset");
mycon.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\Omnivox.mdb");
var txtpassword = Request.QueryString("txtpassword");
var txtuserID = parseInt (Request.QueryString("txtuserID"));
var sql;
sql = "SELECT UserID, UserPassword FROM UserOmnivox WHERE UserID=" +txtuserID+ " AND UserPassword='" + txtpassword + "';";
myrec.Open(sql, mycon);
thank you
UPDATE: It is still not working. The error massage is : no value given for one or more required parameters for the line myrec.Open(sql,mycon)
Change
sql = "SELECT * FROM UserOmnivox WHERE UserID=" +txtuserID "AND UserPassword="'+txtpassword';
to
sql = "SELECT * FROM UserOmnivox WHERE UserID=" +txtuserID + " AND UserPassword='"+txtpassword+"'";
If you'd done any kind of basic debugging, like LOOKING at the query string you're generating, you'd have seen this:
sql = "SELECT [..snip..] UserID=" +txtuserID "AND UserPassword="'+txtpassword
^^--- no space
^--- missing +
which produces
SELECT .... UserID=1234AND userPassword
^^---syntax error, no such field '1234AND'
And then, yes, your quotes are wrong too
sql = "SELECT ... UserID=" +txtuserID "AND UserPassword="'+txtpassword
^------------------^-- one string
^-----------------^-- another string
^---???
It should be
sql = "SELECT * FROM UserOmnivox WHERE UserID=" +txtuserID + " AND UserPassword='" + txtpassword + "';";
I find another more flexible solution is better. Sometimes based on conditions you have one where condition, in others you have zero, and in others you have two. If you go down these paths they don't solve that issue. The following does.....
Some sql query
where 1=1 -- ## A condition that will always be true and does nothing to your query.
and first optional where clause
and second optional where clause
This way if you don't have the first where clause in a given situation but you do have the second you are not missing the words "where". You always have the where and you optionally add any array of "and" parts to your where statement. 100% flexibility in this method works for all challenges. Plus it is easier to follow code once you get past the wtf is this 1=1 nonsense reaction.

Query to retrieve all row data for supplied column name

I am using Eclipse and Oracle SQL Developer. My connections are all set up. I am trying to query my database in SQL Developer by passing in a column name as a variable.
For example, I just want to use something similar to this statement:
select * from CUSTOMERS;
but allow CUSTOMERS to be a variable where I can pass in any table name.
Currently this pulls all column names from given column name and connection:
final String query = "select column_name from all_tab_columns"
+" where owner = ?"
+" and table_name = ?";
try {
headers = DAO.useJNDI(jndi)
.setSQL(query)
.input(1, host)
.input(2, tableName)
.list(String.class);
I want to do the same thing but with rows. Does anyone know how to do this? This is what I am thinking about so far:
final String sql = "select *"
+ " from table_name"
+ " where owner = ? and table_name = ?";
try {
logger.debug(tableName+sourceJNDI);
sourceList = DAO.useJNDI(sourceJNDI)
.setSQL(sql)
.input(1, host)
.input(2, tableName)
.list(DatabaseCompareDto.class);
The main focus is the SQL statements. I know everything else works.
If I'm reading your question correctly, I think what you want is to replace the first table_name in your SQL with ?, then add an additional .input( 1, tableName) :
final String sql = "select *"
+ " from ?"
+ " where owner = ? and table_name = ?";
try {
logger.debug(tableName+sourceJNDI);
sourceList = DAO.useJNDI(sourceJNDI)
.setSQL(sql)
.input(1, tableName)
.input(2, host)
.input(3, tableName)
.list(DatabaseCompareDto.class);
You can't pass the table name as a parameter. Instead of wasting your energy on such an alleged generic solution, use or create a small templating engine which allows you to replace the table name in your query before sending it to the database.

Can't retrieve data from the database

I'm a little in need of your help
In my web application I have this Select statement, but once I run it, it retrieves 0 data but when I try my Select statement in the database it has data in it, and my Select statement is correct, by the way my application is already published in the server.
Here's my code
string SelectStatement = "SELECT DATEDIFF(day, kg1653, GETDATE()) datenum, kg1635, (CASE WHEN kg1637 is null THEN 0 END) eis ";
string FromStatement = "FROM hsi.keygroupdata503 ";
string WhereStatement = "WHERE kg1235='" + _securityCode + "' and kg1241 is null";
_sqlDT = ConnectToDatabase(SelectStatement + FromStatement + WhereStatement);
and here's my connection string
System.Data.Odbc.OdbcConnection _odbcConn = new System.Data.Odbc.OdbcConnection();
_odbcConn.ConnectionString = "MY DATABASE CONNECTION STRING";
System.Data.Odbc.OdbcDataAdapter _odbcA = new System.Data.Odbc.OdbcDataAdapter(sqlQuery1, _odbcConn);
DataTable _odbcDt = new DataTable();
_odbcA.Fill(_odbcDt);
return _odbcDt;
Can somebody please help me with this?
Thank you so much!
When does sqlQuery1 get set to _sqlDT ... your best bet is to debug and see what the query is right on the line of it being called and copy it to run on the SQL server in case something else is updating it or _scurityCode is empty. Also if you have a test environment with similar table names, make sure you are connecting to the same live instance.
Side note, not foolproof but make sure _securityCode has a replace statement and change all single quotes to double quotes to work against SQL injection as the commentor above said.

SQL - Using a prepared statement for the FROM clause?

Is it possible to use a prepared statement for the FROM clause?
I'm trying to do this:
PreparedStatement preStmType = conn.prepareStatement("SELECT * FROM ? WHERE article_id = ?");
preStmType.setString(1, rsetArticle.getString(5));
preStmType.setInt(2, rsetArticle.getInt(1));
It does not seem to work. When I remove the argument for the FROM clause and use it only in the where, it works, but I would like to generate the FROM dynamically too.
Nope, you can't
Prepared statements supports data literals only.
Speaking of this particular case, why do you want to generate fieldlist dynamically? If you don't know what field you need - just select all and then pick one from the returned row
Are you using Java?
How about trying this:
String qryStr = "SELECT * FROM "+rsetArticle.getString(5)+" "
qryStr =qryStr + "WHERE article_id = ?"
PreparedStatement preStmType = conn.prepareStatement(qryStr);
preStmType.setInt(1, rsetArticle.getInt(1));