I am not sure if there is any built-in function in sql server 2008 that will tell whether it is reserved keyword or not.
The reason I wanted to do this is because I find sometimes the column names are using the same name as the reserved keywords, for example, a column called 'desc', 'user', 'state', etc, which then we have to wrap them with square brackets ([desc], [user], [state]) to be able to query the columns correctly.
If such a built-in function does exist, then we probably can do
if isReservedKeyword (#name) = true
set #column = REPLACE(#column, #name, '[' + #name+ ']')
else
set #column = #name
Reserved words are documented here:
http://msdn.microsoft.com/en-us/library/ms189822.aspx
That list is exhaustive, but it's not so long that you couldn't just re-enter those into your own database table to check against.
There is a built in function that will take care of this, and also 'unusual' characters: QUOTENAME
:
Returns a Unicode string with the
delimiters added to make the input
string a valid SQL Server delimited
identifier.
The following example takes the
character string abc[]def and uses the
[ and ] characters to create a valid
SQL Server delimited identifier.
SELECT QUOTENAME('abc[]def')
Here is the result set.
[abc[]]def]
(1 row(s) affected)
Notice that the right bracket in the
string abc[]def is doubled to indicate
an escape character.
Just put brackets around every column. That way you ensure that even reserved words are taken care of.
Related
I am trying to implement a stored procedure that gets the two parameters #startsWith and #endsWith and constructs this query string:
#startswith + '%' + #endsWith
To search for entries of a single column (Name) that start end end with the parameters. Here is the stored procedure:
CREATE PROCEDURE termNameStartsEndsWith(
#startsWith AS nvarchar,
#endsWith AS nvarchar
)
AS
BEGIN
SELECT * FROM Term WHERE
Name LIKE (#startsWith + '%' + #endsWith)
END;
However, I get unexpected results when one of the two query parameters is empty (''). Here is an example where I would expect only results where the Term column entry starts with 'water', but i get a bunch of additional rows:
I dont get these results when executing as a query:
So I expect that the problem is coming from the empty string concatenation being handled differently in a stored procedure? If so, how can I adapt the procedure accordingly?
Thanks for the help in advance.
As noted by Larnu in the comments, the issue isn't the query, it's your parameter declarations.
You have two NVARCHAR(n) parameters declared, but there is no length declared for either of them. From the documentation (emphasis added):
When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified with the CAST function, the default length is 30.
So both parameters are exactly one character long. Conveniently, SQL Server will let you assign a longer value to that parameter, and then just take the first character and silently truncate the rest.
Modify your parameters to have length definitions, and you should be in business.
I need to create a INSERT statement using parameters. Say I have two variable name #DestinationFields, #InsertValues.
Here #DestinationFields contain the column name like: product,price and #InsertValues contains the values for those two columns, like: Book,100.
Now, How i create a insert command to insert those values where each value need to add a quotation mark .I already tried as
I already tried as
EXEC('INSERT into tbl_test('+#DestinationFields+')values('+#InsertValues+')')
But it's returning an error.
The name "book" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some
contexts) variables. Column names are not permitted.
How do I do it? Thanks in advance.
Pretending there is no problem of SQL injection here*, you can quickly fix your code by adding quotation marks around Book. The value of # InsertValues should be
'Book', 100
instead of simply
Book, 100
You need to add quotation marks around each string value; otherwise, strings are interpreted as names, which is not valid.
EDIT : (in response to a comment) If all columns are of varchar type, you can put quotes around the entire string, and replace all commas with the quote-comma-quote pattern, like this:
values('''+REPLACE(#InsertValues,',',''',''')+''')'
* You should not put code like this into production, because it can be manipulated to harm your system rather severely. Here is a good illustration of the problem (link).
Try:
DECLARE #DestinationFields VARCHAR(200);
SET #DestinationFields = 'Col1, Col2, Col3'
DECLARE #InsertValues VARCHAR(200);
SET #InsertValues = '1, 2, 3'
DECLARE #SQLString VARCHAR(1000);
SET #SQLString = 'INSERT INTO tbl_test (' + #DestinationFields + ') VALUES (' + #InsertValues + ')';
EXEC (#SQLString)
However, this is very open to SQL Injection attacks. But, it will do what you require.
The Curse and Blessing of Dynamic SQL
I come from MySQL and the below query doesn't work in Sybase. How should I escape single quotes?
UPDATE Animals SET NAME = 'Dog\'s friends' WHERE uid = 12
If working with Sybase, having got used to MySQL which more database users have experience you may soon discover you are unable to escape single quotes with backslash in.
So how do you escape quotes in Sybase? In fact, in Sybase SQL the single quote acts as the escape character.
See below for an example UPDATE statement in both “languages”:
MySQL
UPDATE Animals SET NAME = 'Dog\'s friends' WHERE uid = 12
Sybase
UPDATE Animals SET NAME = 'Dog''s friends' WHERE uid = 12
I’m not entirely sure this makes sense to me (especially as it looks like a double quote) but there you go!
You can create a custom function to escape quotes :
CREATE FUNCTION "ESCAPE_QUOTES"(in a_string long varchar)
returns long varchar
begin
return replace(a_string, '''', '''''');
end
I searched around quite a bit, it would be great if someone could link me to a solution or answer my query.
The thing is I have a postgresql table that contains a lot of single quotes and I cant figure out how to get rid of them, because obviously this
update tablename set fieldname= NULL where fieldname=' ;
wont work.
Better use replace() for this:
UPDATE tbl SET col = replace(col, '''', '');
Much faster than regexp_replace() and it replaces "globally" - all occurrences of the search string. The previously accepted answer by #beny23 was wrong in this respect. It replaced first occurrences only, would have to be:
UPDATE tbl SET col = regexp_replace(col, '''', '', 'g');
Note the additional parameter 'g' for "globally". Read about string functions in the manual.
Aside: the canonical (and SQL standard) way to escape single quotes (') in string literals is to double them (''). Using Posix style escape sequences works, too, of course. Details:
Insert text with single quotes in PostgreSQL
update tablename set fieldname= NULL where fieldname='''' ;
or
update tablename set fieldname= NULL where fieldname=E'\'' ;
insert into table1(data) values ($$it's a string, it's got some single quotes$$)
Use $$ before and after the string. It will insert data.
In SQL Server, the query
SELECT custid, country, region, city
FROM Sales.Customers
WHERE region = N'WA'
what is the meaning of 'N' in the where clause? I remove it, get same result.
It is casting your literal to a Unicode string.
See here for official explanation:
Unicode strings have a format similar to character strings but are preceded by an N identifier (N stands for National Language in the SQL-92 standard).
In many cases, it won't make a difference, unless your literal contains Unicode characters. If it does, and you leave out the explicit cast, it will convert your Unicode characters to a '?':
select 'Ộ', N'Ộ'
---- ----
? Ộ
Unicode string constants that appear in code executed on the server, such as in stored procedures and triggers, must be preceded by the capital letter N. This is true even if the column being referenced is already defined as Unicode. Without the N prefix, the string is converted to the default code page of the database. This may not recognize certain characters.
For example, the stored procedure created in the previous example can be executed on the server in the following way:
EXECUTE Product_Info #name = N'Chain'
The requirement to use the N prefix applies to both string constants that originate on the server and those sent from the client.
'N' stands for National Language and denotes that you are passing a value for NVARCHAR, NCHAR. The data types that accept languages other than English start with N.
Keep in mind that you are not required to wrap your parameter with 'N' for data types like VARCHAR, CHAR because they don't accept Unicode characters.
Any other language such as Arabic, Farsi will be considered as Unicode so they should be manipulated in data types like NVARCHAR and values should be wrapped with 'N' as below:
DECLARE #Name AS NVARCHAR(50);
SET #Name = N'اسم';
PRINT #Name;
This will return:
اسم
If you try without 'N':
DECLARE #Name AS NVARCHAR(50);
SET #Name = 'اسم';
PRINT #Name;
This will return
???
It is because you haven't wrapped the value with 'N' although the data type is NVARCHAR and system doesn't know anything about the word 'اسم'.