SQL - populating table - sql

EDIT: Thanks guys. It was truly just a formatting error of the single-quotation mark from the source code I copied. Thanks a lot!
Codes:
USE Library;
INSERT INTO myLibrary VALUES (
‘SQL Bible’
,‘Alex Kriegel’
,‘Boris M. Trukhnov’
,‘Wiley’
,888
,‘April 7,2008’
,‘978-0470229064’
,‘English’
);
Output:
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '‘'.
Question
What is the problem here? I am new to SQL. Thanks in advance!

In SQL, strings are defined with the ' characters, not ‘ and ’

Looks like you're using the wrong character to encapsulate your strings. Instead of the ‘ character, you need to use either a ' or a ":
USE Library;
INSERT INTO myLibrary VALUES (
"SQL Bible"
,"Alex Kriegel"
,"Boris M. Trukhnov"
,"Wiley"
,888
,"April 7,2008"
,"978-0470229064"
,"English"
);

If you did a copy/paste from some software, like Word, it can have formatting attached. Your SQL engine will not interpret it.
Take the code, put it into notepad or some other simple text editor (notepad + or jedit are two that I use) and do a replace the open quote and the end quote with a ' or ".

Related

Incorrect syntax near ''

I'm trying to run the following fairly simple query in SQL Server Management Studio:
SELECT TOP 1000 *
FROM
master.sys.procedures as procs
left join
master.sys.parameters as params on procs.object_id = params.object_id
This seems totally correct, but I keep getting the following error:
Msg 102, Level 15, State 1, Line 6
Incorrect syntax near ''.
It works if I take out the join and only do a simple select:
SELECT TOP 1000 *
FROM
master.sys.procedures as procs
But I need the join to work. I don't even have the string '' in this query, so I can't figure out what it doesn't like.
Such unexpected problems can appear when you copy the code from a web page or email and the text contains unprintable characters like individual CR or LF and non-breaking spaces.
Panagiotis Kanavos is right, sometimes copy and paste T-SQL can make appear unwanted characters...
I finally found a simple and fast way (only Notepad++ needed) to detect which character is wrong, without having to manually rewrite the whole statement: there is no need to save any file to disk.
It's pretty quick, in Notepad++:
Click "New file"
Check under the menu "Encoding": the value should be "Encode in UTF-8"; set it if it's not
Paste your text
From Encoding menu, now click "Encode in ANSI" and check again your text
You should easily find the wrong character(s)
The error for me was that I read the SQL statement from a text file, and the text file was saved in the UTF-8 with BOM (byte order mark) format.
To solve this, I opened the file in Notepad++ and under Encoding, chose UTF-8. Alternatively you can remove the first three bytes of the file with a hex editor.
You can identify the encoding used for the file (in this case sql file) using an editor (I used Visual studio code). Once you open the file, it shows you the encoding of the file at the lower right corner on the editor.
encoding
I had this issue when I was trying to check-in a file that was encoded UTF-BOM (originating from a non-windows machine) that had special characters appended to individual string characters
You can change the encoding of your file as follows:
In the bottom bar of VSCode, you'll see the label UTF-8 With BOM. Click it. A popup opens. Click Save with encoding. You can now pick a new encoding for that file (UTF-8)
I was using ADO.NET and was using SQL Command as:
string query =
"SELECT * " +
"FROM table_name" +
"Where id=#id";
the thing was i missed a whitespace at the end of "FROM table_name"+
So basically it said
string query = "SELECT * FROM table_nameWHERE id=#id";
and this was causing the error.
Hope it helps
I got this error because I pasted alias columns into a DECLARE statement.
DECLARE #userdata TABLE(
f.TABLE_CATALOG nvarchar(100),
f.TABLE_NAME nvarchar(100),
f.COLUMN_NAME nvarchar(100),
p.COLUMN_NAME nvarchar(100)
)
SELECT * FROM #userdata
ERROR:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '.'.
DECLARE #userdata TABLE(
f_TABLE_CATALOG nvarchar(100),
f_TABLE_NAME nvarchar(100),
f_COLUMN_NAME nvarchar(100),
p_COLUMN_NAME nvarchar(100)
)
SELECT * FROM #userdata
NO ERROR
For me I was miss single quote in the statement
Incorrect One : "INSERT INTO Customers (CustomerNo, FirstName, MobileNo1, RelatedPersonMobileNo) VALUES ('John123', John', '1111111111', '1111111111)"
missed quote in John' and '1111111111
Correct One: "INSERT INTO Customers (CustomerNo, FirstName, MobileNo1, RelatedPersonMobileNo) VALUES ('John123', 'John', '1111111111', '1111111111')"
I was able to run this by replacing the 'Dot'; with and 'Underscore'; for the [dbo][tablename].
EXAMPLE:
EXEC sp_columns INFORMATION_SCHEMA.COLUMNS
GO //**this will NOT work. But will intelliSence/autocomplete as if its correct.
EXEC sp_columns INFORMATION_SCHEMA_COLUMNS
GO //**This will run in Synapse. but funny enough will not autocomplete.

String appending of Regex in SQL (Microsoft SQL Server 2008 R2)

I'm trying to use the REPLACE function in SQL and I am having problems with trying to append a string to the end of the current contents of a column.
set ActualRegex = REPLACE(ActualRegex, ActualRegex, ActualRegex + '[\d\D]*')
These strings will be used for Regex checks in a C# program, but that's not particularly relevant to the problem.
When I try running this query, i end up getting an error message
Msg 8152, Level 16, State 14, Line 1
String or binary data would be truncated.
The statement has been terminated.
I've checked the field sizes, and the resulting strings will not be nearly long enough to exceed the size of the field (varchar(512)). At biggest they might be 50 characters long unless something strange is happening that I'm unaware about.
Thanks in advance for any help!
EDIT: Here's the full query
update [Registration].[dbo].[MigrationOfTagTypes] set ActualRegex =
REPLACE(ActualRegex, ActualRegex, ActualRegex + '[\d\D]*')
where Regex != '' and Regex like '%\%' escape '\'
EDIT: Actually, I figured it out and turns out I was just being stupid and overlooking something small. Apparently these fields were filled with lots of empty whitespace appended onto the end of the strings, so appending to that would result in breaking the size constraint. Thanks for all the help!
Msg 8152, Level 16, State 14, Line 1
String or binary data would be truncated.
The statement has been terminated.
There are two reasons for this:
Your varchar column is not large enough. Appending 7 characters to an existing 10 into a varchar(15) column won't work
Your column is defined as char (why?!). Char columns have implicit trailing spaces, so if you add 'ABC' to a char(10) field containing 'XYZ', it actually ends up as 'XYZ ABC' (13) which is longer than char(10).
In the 2nd case, i.e. char columns, use RTRIM
update [Registration].[dbo].[MigrationOfTagTypes] set ActualRegex =
RTRIM(REPLACE(ActualRegex, ActualRegex, ActualRegex + '[\d\D]*'))
where Regex != '' and Regex like '%\%' escape '\'
Note: using replace like this allows 'ABCxxxABC' to become 'ABC[\d\D]*xxxABC[\d\D]*'
If you simply wanted to append to the end of the column, then you would use
update [Registration].[dbo].[MigrationOfTagTypes]
set ActualRegex = RTRIM(ActualRegex) + '[\d\D]*'
where Regex != '' and Regex like '%\%' escape '\'
Is it possible that concat is more useful?
As far as the error message goes, I do not know why it is generated, but than again, it has been a while since I used MS SQL for the last time.
I'm thinking it's possible that your column is being aggregated recursively, ad infinitum. Or at least ad 512 characters.
If this is the case, you'll have to offload the current table contents into a temporary table, then use that data to perform the update back onto the original table.
I'm researching if this is possible right now.

Unable to replace Char(63) by SQL query

I am having some rows in table with some unusual character. When I use ascii() or unicode() for that character, it returns 63. But when I try this -
update MyTable
set MyColumn = replace(MyColumn,char(63),'')
it does not replace. The unusual character still exists after the replace function. Char(63) incidentally looks like a question mark.
For example my string is 'ddd#dd ddd' where # it's my unusual character and
select unicode('#')
return me 63.But this code
declare #str nvarchar(10) = 'ddd#dd ddd'
set #char = char(unicode('#'))
set #str = replace(#str,#char,'')
is working!
Any ideas how to resolve this?
Additional information:
select ascii('�') returns 63, and so does select ascii('?'). Finally select char(63) returns ? and not the diamond-question-mark.
When this character is pasted into Excel or a text editor, it looks like a space, but in an SQL Server Query window (and, apparently, here on StackOverflow as well), it looks like a diamond containing a question mark.
Not only does char(63) look like a '?', it is actually a '?'.
(As a simple test ensure you have numlock on your keyboard on, hold down the alt key andtype '63' into the number pad - you can all sorts of fun this way, try alt-205, then alt-206 and alt-205 again: ═╬═)
Its possible that the '?' you are seeing isn't a char(63) however, and more indicitive of a character that SQL Server doesn't know how to display.
What do you get when you run:
select ascii(substring('[yourstring]',[pos],1));
--or
select unicode(substring('[yourstring]',[pos],1));
Where [yourstring] is your string and [pos] is the position of your char in the string
EDIT
From your comment it seems like it is a question mark. Have you tried:
replace(MyColumn,'?','')
EDIT2
Out of interest, what does the following do for you:
replace(replace(MyColumn,char(146),''),char(63),'')
char(63) is a question mark. It sounds like these "unusual" characters are displayed as a question mark, but are not actually characters with char code 63.
If this is the case, then removing occurrences of char(63) (aka '?') will of course have no effect on these "unusual" characters.
I believe you actually didn't have issues with literally CHAR(63), because that should be just a normal character and you should be able to properly work with it.
What I think happened is that, by mistake, an UTF character (for example, a cyrilic "А") was inserted into the table - and either your:
columns setup,
the SQL code,
or the passed in parameters
were not prepared for that.
In this case, the sign might be visible to you as ?, and its CHAR() function would actually give 63, but you should really use the NCHAR() to figure out the real code of it.
Let me give a specific example, that I had multiple times - issues
with that Cyrilic "А", which looks identical to the Latin one, but has
a unicode of 1040.
If you try to use the non-UTF CHAR function on that 1040 character,
you would get a code 63, which is not true (and is probably just an
info about the first byte of multibyte character).
Actually, run this to make the differences in my example obvious:
SELECT NCHAR(65) AS Latin_A, NCHAR(1040) Cyrilic_A, ASCII(NCHAR(1040)) Latin_A_Code, UNICODE(NCHAR(1040)) Cyrilic_A_Code;
That empty string Which shows us '?' in substring.
Gives us Ascii value as 63.
It's a Zero Width space which gets appended if you copy data from ui and insert into the database.
To replace the data, you can use below query
**set MyColumn = replace(MyColumn,NCHAR(8203),'')**
It's an older question, but I've run into this problem as well. I found the solution somewhere else on internet, but I thought it would be good to share it here as well. Have a good day.
Replace(YourString, nchar(65533) COLLATE Latin1_General_BIN2, '')
This should work as well:
UPDATE TABLE
SET [FieldName] = SUBSTRING([FieldName], 2, LEN([FieldName]))
WHERE ASCII([FieldName]) = 63

Replace() on a field with line breaks in it?

So I have a field that's basically storing an entire XML file per row, complete with line breaks, and I need to remove some text from close to three hundred rows. The replace() function doesn't find the offending text no matter what I do, and all I can find by searching is a bunchy of people trying to remove the line breaks themselves. I don't see any reason that replace() just wouldn't work, so I must just be formatting it wrong somehow. Help?
Edit: Here's an example of what I mean in broad terms:
<script>...</script><dependencies>...</dependencies><bunch of other stuff></bunch of other stuff><labels><label description="Field2" languagecode="1033" /></labels><events><event name="onchange" application="false" active="true"><script><![field2.DataValue = (some equation);
</script><dependencies /></event></events><a bunch more stuff></a bunch more stuff>
I need to just remove everything between the events tags. So my sql code is this:
replace(fieldname, '<events><event name="onchange" application="false" active="true"><script><![field2.DataValue = (some equation);
</script><dependencies /></event></events>', '')
I've tried it like that, and I've tried it all on one line, and I've tried using char(10) where the line breaks are supposed to be, and nothing.
Nathan's answer was close. Since this question is the first thing that came up from a search I wanted to add a solution for my problem.
select replace(field,CHAR(13)+CHAR(10),' ')
I replaced the line break with a space incase there was no break. It may be that you want to always replace it with nothing in which case '' should be used instead of ' '.
Hope this helps someone else and they don't have to click the second link in the results from the search engine.
Worked for me on SQL2012-
UPDATE YourTable
SET YourCol = REPLACE(YourCol, CHAR(13) + CHAR(10), '')
If your column is an xml typed column, you can use the delete method on the column to remove the events nodes. See http://msdn.microsoft.com/en-us/library/ms190254(v=SQL.90).aspx for more info.
try two simple tests.
try the replace on an xml string that has no double quotes (or single quotes) but does have CRLFs. Does it work? If yes, you need to escape the quote marks.
try the replace on an xml string that has no CRLFs. Does it work? Great. If yes use two nested replace() one for the CRLFs only, then a second outter replace for the string in question.
A lot of people do not remember that line breaks are two characters
(Char 10 \n, and Char 13 \r)
replace both, and you should be good.
SELECT
REPLACE(field , CHR(10)+CHR(13), '' )
FROM Blah..

How to insert a string which contains an "&"

How can I write an insert statement which includes the & character? For example, if I wanted to insert "J&J Construction" into a column in the database.
I'm not sure if it makes a difference, but I'm using Oracle 9i.
I keep on forgetting this and coming back to it again! I think the best answer is a combination of the responses provided so far.
Firstly, & is the variable prefix in sqlplus/sqldeveloper, hence the problem - when it appears, it is expected to be part of a variable name.
SET DEFINE OFF will stop sqlplus interpreting & this way.
But what if you need to use sqlplus variables and literal & characters?
You need SET DEFINE ON to make variables work
And SET ESCAPE ON to escape uses of &.
e.g.
set define on
set escape on
define myvar=/forth
select 'back\\ \& &myvar' as swing from dual;
Produces:
old 1: select 'back\\ \& &myvar' from dual
new 1: select 'back\ & /forth' from dual
SWING
--------------
back\ & /forth
If you want to use a different escape character:
set define on
set escape '#'
define myvar=/forth
select 'back\ #& &myvar' as swing from dual;
When you set a specific escape character, you may see 'SP2-0272: escape character cannot be alphanumeric or whitespace'. This probably means you already have the escape character defined, and things get horribly self-referential. The clean way of avoiding this problem is to set escape off first:
set escape off
set escape '#'
If you are doing it from SQLPLUS use
SET DEFINE OFF
to stop it treading & as a special case
An alternate solution, use concatenation and the chr function:
select 'J' || chr(38) || 'J Construction' from dual;
The correct syntax is
set def off;
insert into tablename values( 'J&J');
There's always the chr() function, which converts an ascii code to string.
ie. something like:
INSERT INTO
table
VALUES (
CONCAT( 'J', CHR(38), 'J' )
)
You can insert such an string as 'J'||'&'||'Construction'.
It works fine.
insert into table_name (col_name) values('J'||'&'||'Construction');
INSERT INTO TEST_TABLE VALUES('Jonhy''s Sport &'||' Fitness')
This query's output : Jonhy's Sport & Fitness
SET SCAN OFF is obsolete
http://download-uk.oracle.com/docs/cd/B10501_01/server.920/a90842/apc.htm
In a program, always use a parameterized query. It avoids SQL Injection attacks as well as any other characters that are special to the SQL parser.
I've found that using either of the following options works:
SET DEF OFF
or
SET SCAN OFF
I don't know enough about databases to know if one is better or "more right" than the other. Also, if there's something better than either of these, please let me know.
SET ESCAPE ON;
INSERT VALUES("J\&J Construction") INTO custnames;
(Untested, don't have an Oracle box at hand and it has been a while)
If you are using sql plus then I think that you need to issue the command
SET SCAN OFF
Stop using SQL/Plus, I highly recommend PL/SQL Developer it's much more than an SQL tool.
p.s. Some people prefer TOAD.
Look, Andrew:
"J&J Construction":
SELECT CONCAT('J', CONCAT(CHR(38), 'J Construction')) FROM DUAL;