Dynamic SQL string wildcard % causes 'Invalid Column Name' in Visual Studio - sql

Sproc in SQL Server 2005 parses, compiles and runs successfully via SQL Management Studio. I've recently imported the schema into Visual Studio Database Edition 2008 and attempting to 'build' the project.
The collation on both the database I generated the script from , and the 'temporary' design time database are the same (SQL_Latin1_General_CP1_CI_AS)
Code currently looks like this:
DECLARE #SQL varchar(2000)
IF #Username <> ''
SET #SQL = #SQL + ' AND Username LIKE ' + "'" + #Username + "%'"
I receive these errors:
Error 261 TSD4001: Invalid column name '''. (SQL error = 207)
Error 262 TSD4001: Invalid column name '%''. (SQL error = 207)
Is there an approved way of using wildcards in dynamic sql generation that won't break the Visual Studio build process?
Thanks

Try replacing the double quotes with the correct number of single quotes.

Good catch by Mitch Wheat.
You need to escape each single quote character desired in the SQL string, by using two of them consecutively. (The first one "closes" the string but the following one tells the parser this is a single quote within the string)
Specifically, you want:
... ' AND Username LIKE ''' + #Username + '%'''

Are you doing this in C# or VB.Net?
in either case, Replace each single quote with 2 single quotes:
in your client code, if username is a client side variable,
where you call this you need
SQL = SQL + " AND Username LIKE ''" + username + "%''"; c#
SQL = SQL + " AND Username LIKE ''" + username + "%''" vb.Net
or, if you are using parameters (#UserName)
SQL = SQL + " AND Username LIKE ''#Username%''"; c#
SQL = SQL + " AND Username LIKE ''#Username%''" vb.Net

Thanks for the lightning fast responses everyone, really helpful Mitch and mjv. Now to do a sql injection to prove to colleague that it was bum code!

Related

SSIS - Read select from table

I have query in table.
For Example:
SELECT 1 AS pocet_zaznamu " + #[$Package::db]
+ ".ads.ea_meta_auta_sleva
I read data into project.
Now I have:
SELECT 1 AS pocet_zaznamu \" + #[$Package::db] + \".ads.ea_meta_auta_sleva
How I remove back slash from string?
I think you are trying to write an expression in the OLEDB Source SQL Command, but you are writing it in the wrong place.
You can simply add a variable of type string example #[User::strQuery], and change its EvaluateAsExpression property to True, click on the expression field and write the following expression:
"SELECT 1 AS pocet_zaznamu " + #[$Package::db] + ".ads.ea_meta_auta_sleva"
Now go to the OLE DB Source, and change the Data Access mode to SQL Command from variable and select #[User::strQuery]

SQL Like statement not working in Visual Basic

Dim strText As String = tbRefine.Text
Dim sql As String = "SELECT user_name,forename,surname,game_cash,reg_group FROM tblGame WHERE user_name LIKE '" + strSearchText + "' & '*'"
Dim dsRefine As New DataSet
GetDataset(sql, "tblGame", dsRefine)
MsgBox(dsRefine.Tables("tblGame").Rows(0).Item(2).ToString)
This is not working, it crashes and says there is nothing in the dataset.
I know the dataset function works as its worked successfully before.
When i print out the sql statement into microsoft access it works fine. What am i doing wrong
Try this:
"SELECT user_name,forename,surname,game_cash,reg_group
FROM tblGame
WHERE user_name LIKE '%" + strSearchText + "%'"
Try to use the RTRIM() function in your line:
Dim sql As String = "SELECT user_name,forename,surname,game_cash,reg_group
FROM tblGame
WHERE RTRIM(user_name) LIKE '" + strSearchText + "' & '*'"
What about leading or trailing % symbols in your like?
At the moment you will end up with a where clause like:
LIKE 'searchtext''*'
which looks a bit odd (I assume SQL server?).
It's wiser to use SQL parameters as your method is open to SQL injection. The link below will help with how to format the SQL statement. I would also suggest doing it via a store procedure, but hats optional...
http://forums.asp.net/t/1256985.aspx
I think there's one more thing to be mentioned:
the "*" wildcard character works for the "Like" operator in VB/VBA/MS-Access, but not in T-SQL.
The correct wildcard character for the "Like" operator in T-SQL is "%".
That's why this T-SQL statement:
Select... WHERE ... LIKE 'sText*'
returned no data without any syntax error in MS-SQL(using T-SQL), but works in MS-Access.

Keyword search to include Uniqueidentifier field

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.

Remove the last comma in SQL UPDATE statement using StrUtils in Delphi

Assume that we have this SQL statement:
UPDATE article SET saison='12E', mode='ECH', client='SAS', WHERE ID='3448fe81-1bec-e011-8546-001f3ccf8f20'
This SQL statement is generated by concatenated strings like this:
// saison change
procedure TarticleEditForm.saisonComboChange(Sender: TObject);
begin
SQLQuery := SQLQuery + 'saison=''' + saisonCombo.Text + ''',';
end;
// client change
procedure TarticleEditForm.clientComboChange(Sender: TObject);
begin
SQLQuery := SQLQuery + 'client=''' + clientCombo.Text + ''',';
end;
.
.
.
As you see, there is a comma before "WHERE" clause. How can I remove the last comma to have the correct statement:
UPDATE article SET saison='12E', mode='ECH', client='SAS' WHERE ID='3448fe81-1bec-e011-8546-001f3ccf8f20'
RMQ: the number of comma is not fixe, it can be 1, 2, 5...
thank you.
The solution is replacing ", WHERE" by "WHERE"
SQLQuery := StringReplace(SQLQuery , ', WHERE', 'WHERE', [rfReplaceAll]);
I am using this to trace every change in HISTORY Table.
Thank you all.
Rather than concatenating the changes to the SQL string as they happen, store them in a collection and build you SQL string after all the options have been evaluated.
Then you will know how many fields are going to be changed and build the statement correctly. Of course this will require you to store not only the value but also the name of the fild being changed:
[pseudo code]
for i=0 to fields_changed.count {
sql = sql + fields_changed(i).field_name + " = " + fields_changed(i).new_value
if i < fields_changed.count {
sql = sql + ", "
}
}
sql = sql + " WHERE ..."
EDIT: The other option you have is to simply perform a string replace on , WHERE with WHERE just before executing the statement; since the word 'where' is a reserved word and should not occur more than once in your SQL statement. This may be the simpler solution even if it feels like a bit of a hack.
another option is to reduce the length of the string by 1 character before appending the WHERE clause.

Getting "The column name xxx is not valid" exception when trying to combine columns

I am trying to combine two columns in SQL query but getting the following exception in java.sql.ResultSet's FindColumn method:
JdbcSqlException: The column name
FullName is not valid. Column:
'FullName'
Here is my SQL query
SELECT U.FirstName + ' ' + U.LastName AS FullName FROM User as U
Anyone?
Please note that query runs fine when I run it directly in SQL Server management studio. Also, this query is part of a big query that's why U as alias.
When you put "AS FullName", Fullname is a label now. JDBC gets data by "column name" or "field name". You have to change your code (I dont know your prog. language) accordingly.
You might try putting parentheses around the string concatenation, as in
SELECT (U.FirstName + ' ' + U.LastName) AS FullName FROM User U
Share and enjoy.
Sorry I am answering this late. I am sure someone will need the answer. I have had the same problem and whereas I do not know exactly why and what causes it, I have found a way to fix it (at least for my case).
jahanzeb farooq did not show his code but if you had declared the PreparedStatement and ResultSet variables variables outside the current method and used them in other queries then try declaring them anew inside the current method, that is
PreparedStatement pst=conn.prepareStetement(sql);
ResultSet rs=pst.executeQuery();
The problem will be sorted (or at least fixed)
String sql = "SELECT U.FirstName + ' ' + U.LastName AS FullName FROM User U ";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if (rs.next()) {
String fullname = rs.getString("FullName");
jtextfiel.setText(fullname);
//////or - short
jtextfiel.setText(rs.getString("FullName"));
}