How to fix error when value in SQL contains an apostrophe - sql

I am updating a string in a table using a Firebird SQL statement, with information typed by a user. However, if the string entered by a user has an apostrophe then it creates an error because the SQL syntax no longer reads correctly.
I guess I could read the string and remove all instances of apostrophes, but I wonder if there is an easier way.
{Edit 17 May 2017}
I am using Firebird 2.5 (as part of a software program called Ostendo)
Here is an extract of the code:
UpdatedMsg := frmPOLineNotesMemo.Lines.text;
SQLUpdateStr := 'update ASSEMBLYLINES set LINENOTES = LINENOTES || '''+ UpdatedMsg +''' Where SYSUNIQUEID = ' + AssyPropertyLine + '';
ExecuteSQL(SQLUpdateStr);
frmPOLineNotesMemo.Lines.Text is information entered by the user via a form.

You need to double the apostrophes in the string.
Found here: https://firebirdsql.org/manual/qsg10-firebird-sql.html
However keep in mind the comments. User input should be passed as parameters to avoid security problems.

Related

Pass a variable into a SQL query in Excel Power Query

Long story short, I have a sql query pulling data from a database into a spreadsheet. I want to be able to change the Plant filter inside the query via Power Query, I have tried using a custom function and adding that into the query where the variable is set (see below)
Sql.Database("server", "database", [Query="DECLARE #FilterOnPlant AS varchar(3)#(lf)SET #FilterOnPlant = '" + filterOnPlant + "'#(lf)#(lf)SELECT
In doing this I keep getting the following error:
Expression.Error: We cannot apply operator + to types Text and Table.
Details:
Operator=+
Left=DECLARE #FilterOnPlant AS varchar(3)
SET #FilterOnPlant = '
Right=[Table]
I figure it has something to do with the '+' operator used but can't find an alternative.
I have tried using:
'&'
'+'
'and'
but they all yield the same error (with the exception of 'and' that error states that it's not being used in a logical statement which makes sense)
For further info:
The custom function to get the value I want is:
filterOnPlant = Excel.CurrentWorkbook(){[Name="Active_Plant"]}[Content]
The intention is to get the Value from a cell Named "Active_Plant"
EDIT:
after further testing I have found the issue lies with variable filterOnPlant, when I exchange that for a string value then the query works as expected. If anyone knows how I can get CELL().Value of a named range in power query would be super helpful
Solved!
In my filterOnPlant function I was missing {0}[Column1]
Original: filterOnPlant = Excel.CurrentWorkbook(){[Name="Active_Plant"]}[Content]
New (Working): filterOnPlant = Excel.CurrentWorkbook(){[Name="Active_Plant"]}[Content]{0}[Column1]

How to construct regex for password in SQL?

I'm creating a new stored procedure for user register on my web application. I need to validate user password to be in a format of:
It must contain at least one number or letter
It must contain at least one special character
I need to manage to write this using regex.
This is for a new Database that i have created in SQL server 2017. My database is okay working fine and also my email validation is fine and working.
IF (#password NOT LIKE '%[a-zA-Z0-9]%' OR #password NOT LIKE '%~!##$%^&*()_+-={}[]:"|\;,./<>?''%' OR LEN(#password) < 8)
BEGIN
SET #message = 'Invalid credentials'
RETURN;
END
ELSE
SET #message = 'Success'
RETURN;
END
this is my code so far ad honestly i tried a lot of combinations and still nothing.
I expect the output for a password like !Password123 to be Success but instead i'm still getting "Invalid credentials" and for password like Password123! i am still getting "Invalid credentials"
While it would be ideal to have access to a full regex engine, which would let you write a more robust password check, you actually can handle your requirements using SQL Server's enhanced LIKE operator. The problem I see with your current code is that you are not escaping the square brackets in the second LIKE expression which checks for the presence of a special character. You may tell SQL Server how you plan to escape square brackets using ESCAPE as follows:
DECLARE #password VARCHAR(500);
SET #password = '!Password123';
SELECT 1
WHERE
#password NOT LIKE '%[a-zA-Z0-9]%' OR
#password NOT LIKE '%[~!##$%^&*()_+-={}\[\]:"|\;,./<>?'']%' ESCAPE '\' OR
LEN(#password) < 8;
The above query returns nothing, indicating that !Password123 is a valid password.

Zoho Creator making a custom function for a report

Trying to wrap my head around zoho creator, its not as simple as they make it out to be for building apps… I have an inventory database, and i have four fields that I call to fill a field called Inventory Number (Inv_Num1) –
First Name (First_Name)
Last Name (Last_Name)
Year (Year)
Number (Number)
I have a Custom Function script that I call through a Custom Action in the form report. What I am trying to do is upload a CSV file with 900 entries. Of course, not all of those have those values (first/last/number) so I need to bulk edit all of them. However when I do the bulk edit, the Inv_Num1 field is not updated with the new values. I use the custom action to populate the Inv_Num1 field with the values of the other 4 fields.
Heres is my script:
void onetime.UpdateInv()
{
for each Inventory_Record in Management
{
FN = Inventory_Record.First_Name.subString(0,1);
LN = Inventory_Record.Last_Name.subString(0,1);
YR = Inventory_Record.Year.subString(2,4);
NO = Inventory_Record.Number;
outputstr = FN + LN + YR + NO;
Inventory_Record.Inv_Num1 = outputstr;
}
}
I get this error back when I try to run this function
Error.
Error in executing UpdateInv workflow.
Error in executing For Each Record task.
Error in executing Set Variable task. Unable to update template variable FN.
Error evaluating STRING expression :
Even though there is a First Name for example, it still thinks there is none. This only happens on the fields I changed with Bulk Edit. If I do each one by hand, then the custom action works—but of course then the Inv_Num1 is already updated through my edit on success functions and makes the whole thing moot.
this may be one year late, you might have found the solution but just to highlight, the error u were facing was just due to the null value in first name.
you just have put a null check on each field and u r good to go.
you can generate the inv_number on the time of bulk uploading also by adding null check in the same code on and placing the code on Add> On Submt.( just the part inside the loop )
the Better option would be using a formula field, you just have to put this formula in that formula field and you'll get your inventory_number autogenerated , you can rename the formula_field to Inv Number or whaterver u want.
Since you are using substring directly in year Field, I am assuming the
year field as string.else you would have to user Year.tostring().substring(2,4) & instead of if(Year=="","",...) you have to put if(Year==null , null,...);
so here's the formula
if(First_Name=="","",First_Name.subString(0,1))+if(Last_Name =="","",Last_Name.subString(0,1)) + if(Year=="","",Year.subString(2,4)+Number
Let me know ur response if u implement this.
Without knowing the datatype its difficult to fix, but making the assumption that your Inventory_Record.number is a numeric data item you are adding a string to a number:
The "+" is used for string Concatenation - Joiner but it also adds two numbers together so think "a" + "b" = "ab" for strings but for numbers 1 + 2 = 3.
All good, but when you do "a" + 2 the system doesn't know whether to add or concatenate so gives an error.

Inserting string which contain single quotes ' in SQL

I've seen so many solutions to this that I don't know which one to follow.
I thought that what I have would work but upon further testing I have discovered that this is not true.
I'm using VB to pick up MS Excel worksheets from a given file directory, extract the data, and insert into SQL data tables.
here's the part I need some help with:
If saRet(linex, 11) <> "" Then
IntDesc = (saRet(linex, 11).ToString.Replace("'", "''"))
Echo("Internal description: " & IntDesc)
Else
Echo("No internal description given")
IntDesc = ""
End If
After tampering around with some test insert statements in SQL server studio I thought that replacing ' with '' worked. Sadly, not.
Here's an example of a string which makes the insert fail:
Set-up and Config of New Button on BP and UDF's for Despatch Process
and after my string manipulation, here's the Insert statement(I've blanked out some data which my company probably doesn't want to share, it's insignificant anyway):
NSERT INTO <tablename> VALUES ('2013-12-10', '12', '2013', 'AAAA', 'AAAA', '10668', 'JBT', 'Project - Config & System Build', 'CSB', '2', 'Y', 'N', '0', 'Set-up and Config of New Button on BP and UDF's for Despatch Process', 'Set-up and Config of New Button on BP and UDF''s for Despatch Process', '0', 'NULL')
Very grateful for any help!
Thanks.
The best way is always using parameters. Those handle everything for you and you don't need to do any escaping.
If you can't use parameters, you have to do the encoding yourself, and that's very tricky. One way would be to use a format you can encode safely - for example, instead of inserting as a string literal, you might use binary encoding (eg. cast(0xAABBCCDD as varchar(max))). This is perfectly safe, since you can be sure that there's no invalid character that would break it. Of course, it also has its problems.
As for your example, replacing ' with '' works fine (although of course you'd have to watch out for other invalid characters, such as endlines). Your problem is that you didn't do the encoding on all the strings. In your sample, the last string has the proper encoding, the one before it does not. This also beautifully illustrates the pain of making sure you're encoding properly - and everything you miss means an error, or even a way to exploit the code and cause harm. For example, what if the description was ', ''0'', ''NULL''); delete from users --?

NHibernate SQL query issue with string parameter

I got a problem with this code:
string sql = "select distinct ruoli.c_tip_usr"
+ " from vneczx_ute_app_trn ruoli"
+ " join vnecyd_ent_prf ind"
+ " on ruoli.c_ent = ind.c_ent"
+ " where ruoli.c_app = :appCode"
+ " and ruoli.c_ute_mat = :matricola"
+ " and ind.t_des_ent = :indirizzo";
var ruoli = session.CreateSQLQuery(sql)
.SetString("appCode", Config.Configurator.Istance.ApplicationCode)
.SetString("matricola", user.Matricola)
.SetString("indirizzo", indirizzoCasella)
.List<string>();
This code is correctly executed, the query logged is correct, and the parameter passed correctly evaluated... but it doesn't return any result at all.
Copying the query from the debug console and executing it directly in an Oracle client application (SQL Developer), it gets 2 results (the results I expect to be right).
I found out that the problem is in the last parameter indirizzo, and should depend on the fact that it contains a special char # (indirizzo is an email address).
So I ended up using this solution:
string sql = "select distinct ruoli.c_tip_usr"
+ " from vneczx_ute_app_trn ruoli"
+ " join vnecyd_ent_prf ind"
+ " on ruoli.c_ent = ind.c_ent"
+ " where ruoli.c_app = :appCode"
+ " and ruoli.c_ute_mat = :matricola"
+ " and ind.t_des_ent = '" + indirizzoCasella + "'";
var ruoli = session.CreateSQLQuery(sql)
.SetString("appCode", Config.Configurator.Istance.ApplicationCode)
.SetString("matricola", user.Matricola)
.List<string>();
But it gives me thrills! Aren't the parameters in a query supposed to handle specifically this situation, and thus handle themselves situations with special char, and so on?
Why here a string concatenation works better that a parametric query?
Isn't there a way to force the NHibernate engine to escape some special char?
Update:
I found out how to solve this particular issue: usign the trim command on the field who raise the problem, the problem disappears.
So last line of my sql string now is:
+ " and trim(ind.t_des_ent) = :indirizzo";
I can't understand why it solves the problem thought. Not the field, nor the variable contains empty chars and copying th query on SQL Developer works in both way.
So we have some luck soving the problem, but we have no idea why now it works?
Any thoughts?
even I was facing the same issue, but your hint using TRIM for column saved my day. Since I was looking for a long time, but not able to figure it out.
Along with that, I was able solve my issue by doing the below changes as well:
We were using CHAR datatype some of the columns which used in the query where clause. This was causing the issue to fetch the data from NHibernate. We changed the data type of that column from CHAR to VARCHAR2 and even updated the data with actual size and removed the TRIM from Where clause, the TRICK WORKED!!!! :)
So, any one face this kind of issue, first check whether you are having any column with CHAR and then change to VARCHAR2.
But one more thing you have to remember is: if you are running your application from ASP.Net Development Server, close it and re-run your application. Since if the opening Asp.Net Development Server and if you make any changes to datatype that will NOT be refreshed in your oracle connection. So, better you close the ASP.Net Development server and then re run the application.
Hope my points will help somebody in future!!
Regards,
Sree Harshavardhana
You are not using parameters in a SQL query if you want SQL parameters use a SQL stored proc