How Do I Insert A String Value With Quotes Into A Nvarchar Column
Jul 20, 2007
I am reading data from another data source and storing it in the sqlce database. Some of the string values I'm trying to insert into the database have single quotes in the string (i.e. Johnny's Company). When I try to insert the values with the single quotes, it throws an exception. The code I use to insert the records is as follows:
cmd.CommandText = "INSERT sy_company " +
" (company_id, company, co_name, companyid) " +
"VALUES(" +
"'" + dtSYCompany.Rows[x]["company_id"] + "'," +
"N'" + dtSYCompany.Rows[x]["company"] + "'," +
"N'" + dtSYCompany.Rows[x]["co_name"] + "'," +
"'" + dtSYCompany.Rows[x]["companyid"] + "')";
cmd.ExecuteNonQuery();
When the company name (co_name) has a single quote in it, I get the error. How do I write the insert statement so it will work even though the value being inserted into co_name has a single quote in it?
Thanks so much!
View 3 Replies
ADVERTISEMENT
Dec 28, 2006
My code results in SQL statements like the following one - and it gives an error because of the extra single-quotes in 'it's great':
UPDATE Comments SET Comment='it's great' WHERE UserID='joe' AND GameID='503'
Here's the error I get when I try this code in SQL Server:
Msg 102, Level 15, State 1, Line 1Incorrect syntax near 's'.Msg 105, Level 15, State 1, Line 1Unclosed quotation mark after the character string ''.
I need to know how I can insert a string such as 'it's great' - how do I deal with the extra quotes issue? is there a way to ecape it like this 'it/'s great' ? This doesn't seem to work.
Here's the code that generates the SQL. I'm using a FCKeditor box instead of a TextBox, but I got the same error when I was using the TextBox:
string strUpdate = "UPDATE Comments SET Comment='";strUpdate = strUpdate + FCKeditor1.Value;//strUpdate = strUpdate + ThisUserCommentTextBox.Text;strUpdate = strUpdate + "' WHERE UserID='";strUpdate = strUpdate + (string)Session["UserID"];strUpdate = strUpdate + "'";strUpdate = strUpdate + " AND GameID='";strUpdate = strUpdate + Request.QueryString["GameID"];strUpdate = strUpdate + "'";
SqlConnection myConnection = new SqlConnection(...);SqlCommand myCommand = new SqlCommand(strUpdate, myConnection);
try{myCommand.Connection.Open();myCommand.ExecuteNonQuery();}catch (SqlException ex){ErrorLabel.Text = "Error: " + ex.Message;
}finally{myCommand.Connection.Close();}
I'm using SQL Server 2005 and ASP.NET 2.0
Much thanks
View 5 Replies
View Related
Aug 28, 1998
Hi,
How to insert a string value with quotes in it in SQL Server?
This is not working:
insert table_name values(`abc`d`)
I tried to put escape in front of `, still failed.
Thanks in advance.
-Jenny Wang
View 2 Replies
View Related
Jun 21, 2004
Hey folks, the question is fairly simple, unfortunately the answer has proven rather elusive.
Is it possible to declare a variable which would then be used to identify either a column or table in an SQL statement?
Here's a basic idea of what I'd like to do:
DECLARE @myVar AS NVARCHAR(50)
SELECT *
FROM @myVar
or
DECLARE @myVar AS NVARCHAR(50)
SELECT @myVar
FROM MyTable
I'm probably looking for some sort of built in function that will accept an argument here... like COLUMN(@myVar) or something of the like. I just don't know where to look...
View 1 Replies
View Related
Aug 21, 2007
Hi,
I have a problem with BULK INSERT. I created the following table:
Code Snippetcreate table Test
(id char(4), name nvarchar(16), last char(1))
I am trying to bulk insert data from ASCII (not unicode) file with only two rows:
0011First name
0018Second name
Since it is a fixed length file, I am using the following format file:
Code Snippet
8.0
3
1 SQLCHAR 0 4 "" 1 ID HEBREW_CI_AS
2 SQLCHAR 0 16 "" 2 NAME HEBREW_CI_AS
3 SQLCHAR 0 0 "
" 3 Last HEBREW_CI_AS
With bcp utility everything works just fine!
Code Snippet
bcp Demo.dbo.test in c: est -T -f c: est.fmt
But when I use BULK INSERT in the following form:
Code Snippet
BULK INSERT Test FROM 'c:Test'
WITH
(
FORMATFILE='c:Test.fmt',
CODEPAGE='OEM'
);
I am getting error
Server: Msg 4863, Level 16, State 1, Line 1
Bulk insert data conversion error (truncation) for row 1, column 2 (name).
Now, one interesting thing: if I change the name field from nvarchar to varchar, it is working with BULK INSERT as well.
Can anybody explain what is going on here?
I am using MS SQL 2000 and MSDE
Thanks in advance,
Eugene.
View 2 Replies
View Related
Dec 9, 2013
I have SQL Server 2012 SSIS. I have Excel source and OLE DB Destination.I have problem with importing CustomerSales column.CustomerSales values like 1000.00,2000.10,3000.30,NotAvailable.So I have decimal values and nvarchar mixed in on Excel column. This is requirement for solution.However SSIS reads only numeric values correctly and nvarchar values are set as Null. Why?
CREATE TABLE [dbo].[Import_CustomerSales](
 [CustomerId] [nvarchar](50) NULL,
 [CustomeName] [nvarchar](50) NULL,
 [CustomerSales] [nvarchar](50) NULL
) ON [PRIMARY]
View 5 Replies
View Related
Aug 8, 2001
Hi,
Your help would be appreciated if you could give me some idea about why SQL 2000 takes single quote(') as a default for string searching instead of double quotes("). I have couple of stored procedures which were developed with string comparison with double quotes in SQL 6.5. If any one knows how I can change default as a double quotes(") instead of single quote(') in SQL 2000, would be great. Thanks
View 1 Replies
View Related
Oct 18, 2005
I am trying to build a dynamic where statement for my sql stored prcoedure
if len(@Office) > 0 select @strWhereClause = N'cvEh.chOfficeId in (select id from dbo.csfParseDeLimitedText( ' + @vchOffice + ',' + ''',''' + '))' + ' and ' + @strWhereClause
In this case users can enter comma delimited string in their search criteria. So if they enter we1, we2, we3 then my sql statement should look like
select @strWhereClause = cvEh.chOfficeId in (select id from dbo.csfParseDeLimitedText('we1', 'we2', 'we3'),',')
My csfParseDeLimitedText function looks like this
Create FUNCTION [dbo].[csfParseDeLimitedText] (@p_text varchar(4000), @p_Delimeter char(1))RETURNS @results TABLE (id varchar(100))ASBEGIN declare @i1 varchar(200)declare @i2 varchar(200)declare @tempResults Table (id varchar(100))while len(@p_text) > 0 and charindex(@p_Delimeter, @p_text) <> 0beginselect @i1 = left(@p_text, charindex(@p_Delimeter, @p_text) - 1)insert @tempResults select @i1select @p_text = right(@p_text, len(@p_text) - charindex(@p_Delimeter,@p_text))endinsert @tempResults select @p_text
insert @resultsselect *from @tempResultsreturnEND
My problem is it does not put quotes around the comma delimited stringso I want to put 'we1' , 'we2'. These single quotes are not coming in the dynamic sql statement. How can I modify my query so that single quotes around each entry should show up.
Any help will be greatky appreciated.
Thanks
View 1 Replies
View Related
Dec 14, 2005
I'm constructing a SQL string that needs single quotes in the WHERE clause. How do I encapsulate them in a string variable. I looked into ESCAPE and SET QUOTED_IDENTIFIER, but i don't really see any examples using string Concatenation. I'm trying to filter out the zls (0 length strings)
This doesn't work (all single quotes):
@sqlString = ' SELECT * FROM myTbl '
@sqlString = @sqlString + 'WHERE fld1 <>'' '
Thanks,
Carl
View 5 Replies
View Related
Jan 17, 2008
Hello,
how can I use the following statement with OPENQERY syntax:
SELECT 'hello world' FROM mytable
Maybe I have to transform quite a few and complex SQL-statements to the OPENQUERY syntax. Obviously I have problems with single quotes
SELECT * FROM OPENQUERY(LINKEDSERVER, 'select 'hello world' from mytable')
quotename('hello world', '''') does not help because this will create 'hello world' instead of hello world (w/o quotes).
How can I transform my SQL-statements with quotes to Openquery syntax?
regards
arno
View 4 Replies
View Related
Apr 9, 2015
I have data in a trace file, and I need to extract some info such as phone number.The problem is the phone number could be varying lengths, and various positions in the row.
For example:
@City='New York', @Phone='2035551212' (10 characters, no dashes)
or
@City='San Francisco', @Phone='918-555-1212' (12 characters, with dashes)
or
@City+'Berlin', @Phone='55-123456-7890' (14 characters, with dashes)
I can use CHARINDEX to search & find @Phone=' so I know where the phone number starts, but stuck on a programatic way to find the data between the quotes since it can vary.
View 4 Replies
View Related
May 26, 2008
Hi,
I need to concatenate a string with an int variable on a stored procedure; however, i looks like i am lost in single and double quotes. Does any one know the right comination of quotes for this please? My Code is below:
1 @Price int
2
3 DECLARE @SqlPrice varchar(50)
4
5 if (@Price is not null)
6
7 set @sqlPrice = 'AND price' + '' > '' + '' + @Price + ''
8
View 4 Replies
View Related
Jul 9, 2007
I have a Foreach loop that dynamically builds a query that gets submitted to a Progress 9.1d database. The "SELECT" portion of the query is static - the WHERE clause is built dynamically each pass through the for each loop. The vast majority of the columns have a dash ("-") in their names, so the query passed to progress has to have double quotes surrounding the column names. Not a big deal you would think. If I am retrieving 3 columns, my string would look like "SELECT ""manager-name"", ''"employee-name"", ""date-of-hire"" FROM PUB.EmployeeTable" - with the columns requiring quoted identifiers escaped with double quotes. My script task adds some additional info to the WHERE clause based on other conditions. Once my script task has built the query string, it assigns that string value to my Dts.Variables("SqlString") variable.
I can put a MsgBox() call in the Script task to display my query once it has been built (displaying Dts.Variables("SqlString").Value) - and it looks fine. Using the above example, it would simply be: SELECT "manager-name", "employee-name", "date-of-hire" FROM PUB.EmployeeTable.
So - My foreach loop is set up so that the query command is pulled from my Dts.Variables("SqlString") variable. It fails anytime my query has a column that requires quotes around it. I was confused, since I could take the exact query string displayed by my test MsgBox() and validate it's syntax against our Progress database (and even run it) and it worked fine.
So - I then inserted a breakpoint to break on PreExecute for the DataReader task (next task after Scrip task) to view the value of the Dts.Variables("SqlString") variable just before it gets assigned to the DataReader's Sql Command property. That's when I noticed that the value of the Dts.Variables("SqlString") in the Watch window actually showed that the "double" double quotes I had entered in the SELECT clause (to escape to one double quote) were being replaced with " (slash quote). SO - in the Watch window, my Dts.Variables("SqlString").Value reads as follows:
SELECT "manager-name", "employee-name","date-of-hire" FROM PUB.EmployeeTable.
Obviously, that query is not going to fly via SQL-92/ODBC connection to our Progress database. I've tried everything I can think of - even trying to replace "" with "" in the Foreach expression editor where the Sql Command of the data reader gets assigned. I'm at a total loss. Why would SSIS plug in what looks like C# character escaping syntax when all the expressions are supposed to be VB.NET? I've already successfully run several packages that query our Progress databases that do NOT use the double quotes in the SELECT clause and they work fine. Does anyone have any ideas??
View 3 Replies
View Related
Nov 7, 2006
When users enter text into a textbox, to be INSERTed into my table, SQL Server throws an error if their text contains a single quote.
For example, if they enter "It's great!" then it causes this error:Error: Incorrect syntax near 's'. Unclosed quotation mark after the character string ''.
How can I allow text with single quotes to be inserted into the table?
Here's my code:
string strInsert = "INSERT INTO [Comments] ([GameID], [UserID], [Comment]) VALUES (@GameID, @UserID, @Comment)";
SqlConnection myConnection = new SqlConnection(<<myconnectionstuff>>);SqlCommand myCommand = new SqlCommand(strInsert, myConnection);
myCommand.Parameters.Add( "@GameID", Request.QueryString["GameID"] );myCommand.Parameters.Add( "@UserID", (string)Session["UserID"] );myCommand.Parameters.Add( "@Comment", ThisUserCommentTextBox.Text );
try {myCommand.Connection.Open();myCommand.ExecuteNonQuery();}
catch (SqlException ex) {ErrorLabel.Text = "Error: " + ex.Message;}
finally {myCommand.Connection.Close();}
View 10 Replies
View Related
May 24, 2006
I have a problem with inserting a string with single quotes. For instance,
string testme = "we don't have anything";
insert into tableone (buff) values ("'" + testme + "'");
I get an error with the word "don't" with single quote. But if I delete the single quote "dont" then it inserts okay. Is is a bug in sql 2005? Please help. Thanks.
blumonde
View 2 Replies
View Related
Sep 6, 2000
Hi,
I want to import in a table a file like this one, with a comma separator:
France, 1 , 1
"Congo,Démocratique", 1,2
Is there any options for Bulk Insert like this in Sybase :
LOAD [ INTO ] TABLE [ owner ].table-name [( column-name , ... )]
FROM 'filename -string '
[ load-option ... ]
Parameters
load-option :
CHECK CONSTRAINTS { ON | OFF }
| DEFAULTS { ON | OFF }
| DELIMITED BY string
| ESCAPE CHARACTER character
| ESCAPES { ON | OFF }
| FORMAT ASCII
| QUOTES { ON | OFF }
| STRIP { ON | OFF }
| WITH CHECKPOINT { ON | OFF }
or should we change the pre processing of our log files ??
Thanks to your answers
Axel
View 2 Replies
View Related
Nov 12, 2007
Hi all
I am importing a csv, there are quotes around all the field data which i would like to remove on import.
Is this possible??
Thanks
Rich
View 2 Replies
View Related
Jul 23, 2005
hi,just wanted to know if i need to insert a string with double quotes init into a sql server table, do i need to use any delimeters, like "?an insert like:insert into producttable values(key, "double quote text")where i need the "double quote text" to go in like that, with the " "at both ends.Thank you.
View 1 Replies
View Related
Jun 17, 2014
I imported data from flat file to SQL Server database table. After execution one of column got data with double quotes. It look like:
22222.....02/14/2014....."Smith, John"
333........02/14/2014....."Brownies, Alian"
How to remove quotes?
View 3 Replies
View Related
May 14, 2007
How do you replace quotes in an expression
I mean for example if I needed to replace xx in a string with empty string then the following works: REPLACE(SelectedString, "xx","")
But the example I have needs to actually replace quote marks in a string with an empty string and REPLACE(SelectedString, " " ","") doesn't work. I tried guessing a few option like "E or &QTE or something...
Any ideas ?
Thanks
Richard
View 1 Replies
View Related
Jan 16, 2007
I know this issue has been raised here before, but I have a different angle/question on it.
Flat File source, SQL Destination. No column from the source file has a consistent real width, just consistent to be less that the SQL column.
Issue:
CHAR(12), SMALLINT, CHAR(78), BIGINT
"100012",0,"This is the ""Memo"" of the record, it needs to be imported.",12
This row errors out due to the double quotes around the word MEMO. Additionally, the entire package stops processing due to there being a comma in the memo after the quote encapsulation is escaped.
Has this issue been addressed in any of the SP's? If not, how about this thinking:
1.) Character index the pattern ," and take the value of the first instance of the pattern.
2.) Character index the pattern ", and take the LAST instance of the pattern (ignoring the pattern match after the first column).
3.) Replace all double qoutes between the values of the indexes with single quotes.
4.) Proceed with the Comma separated, quote encapsulated import.
Any thoughts? Additionally, if this seems like it may work, does anyone have a clue how to program this in SSIS, or would I be better to run my files through a VBScript parser to accomplish this first?
Thanks in advance.
View 6 Replies
View Related
Jun 8, 2007
Hi!
Is there any way to store UTF-8 encoded string in Nvarchar field? Or strings can be stored only in Unicode?
View 3 Replies
View Related
Jan 31, 2008
I have used a query statement with the following WHERE string to 'Fill' a dataset.
"AND (A.ApptsDate > '" & strApptPreDate & "' OR (A.ApptsDate = '" & strApptPreDate & "' AND A.ApptsTime >= '" & strApptPreTime & "' ))" & _ and strApptPreTime is defined as:Dim strApptPreTime As String = SomaShared.strPadTime(CStr(dApptCalcNewDate.Hour) + ":" + CStr(dApptCalcNewDate.Minute))
Somehow, the dataset showed only the ApptsTime after 10 am. After more than 2 weeks of debugging, I still can see a dataset watch for > 10 amAppsTime only. Now I am guessting, the problem is 9 is different from 10 - 16, it all because 9 is single digit. Then I check the data type settings for these variables. Here are what I found:
In SQL Server Agent job, the ApptsTime data was 'inserted' by @NewApptTimes, which is declared as char(5).In SQL Server database, the ApptsTime was defined as nvarchar(15).
My question are: 1. The reason why there were no 9 am data for the dataset, is becasue 9 am of nvarchar(15) is not > 8:30 of strApptPreTime? 2. If the answer to the quation 1 is yes, how do I define AppsTime and/or strApptPreTime?
TIA,Jeffrey
View 6 Replies
View Related
Mar 29, 2004
hi
i have connected my ms sql 2000 with C using ODBC
can u help me to return the utf 8 string from nvarchar field ??
how should i do it
please help!!!!!!!
View 6 Replies
View Related
Sep 20, 2005
How do I get a single quote (') in a NVARCHAR string in MS SQL Server?e.g. SELECT @strsql = "SELECT * FROM tblTest WHERE Field1 Like 'blah''Obviously this is invalid as the single quote before "blah" would end thevarchar string.How do I get round this?
View 8 Replies
View Related
Nov 8, 2006
MS SQL 2000. Does anyone know how to find all rows where an nvarchar column contains a specific unicode character? Is it possible without creating a user defined function? Here's the issue. I have a table Expression (ExpID, ExpText) with values like 'x < 100' and 'y ≤ 200'. where the second example contains Unicode character 8804 [that is, nchar(8804)]. Because it's unicode, I don't seem to be able to search for it with LIKE or PATINDEX. These fail:
SELECT * FROM Expression WHERE ExpText LIKE '%≤%' -- no recordsSELECT * FROM Expression WHERE PATINDEX('%≤%', ExpText) -- no records
However, SELECT PATINDEX('%≤%', 'y ≤ 200') will return 3.
Any suggestions? Thanks in advance.
View 3 Replies
View Related
Jan 3, 2002
I had a procdure in SQL 7.0 in which I am using both single quote and double quotes for string values. This proceudreused to work fine in SQL 7.0 but when I upgraded SQL 7.0 to SQL 2000, this proceudre stopped working. When I changed the double quotes to single quotes, it worked fine.
Any Idea why ??
Thanks
Manish
View 2 Replies
View Related
Apr 14, 2015
how SQL 2012 would treat a literal string for a comparison similar to below. I want to ensure that the server isn't implicitly converting the value as it runs the SQL, so I'd rather change the data type in one of my tables, as unicode isn't required.
Declare @T Table (S varchar(2))
Declare @S nvarchar(255)
Insert into @T
Values ('AR'), ('AT'), ('AW')
Set @S = 'Auto Repairs'
Select *
from @T T
where case @S when 'Auto Repairs' then 'AR'
when 'Auto Target' then 'AT'
when 'Auto Wash' then 'AW' end = T.STo summarise
in the above would AR, AT and AW in the case statement be treated as a nvarchar, as that's the field the case is wrapped around, or would it be treated as a varchar, as that's what I'm comparing it to.
View 3 Replies
View Related
Mar 18, 2008
I'm running into this error message when passing in a few records in particular to a function, the only difference I could find is that these recods have about 60k characters on the field that I'm passing to a function.
is there a max lenght for passing to a function?
select function ( field) as results
It's been working fine until today and all of the related fields are declared as nvarchar(max)
Thank you.
View 5 Replies
View Related
Dec 19, 2005
Problem about pass a big string (over 8000 characters) to a variable nvarchar(max) in stored procedure in SQL 2005!
I know that SQL 2005 define a new field nvarchar(max) which can stored 2G size string.
I have made a stored procedure Hellocw_ImportBookmark, but when I pass a big string to @Insertcontent , the stored procedure can't be launch! why?
create procedure Hellocw_ImportBookmark @userId varchar(80), @FolderId varchar(80), @Insertcontent nvarchar(max)
as declare @contentsql nvarchar(max); set @contentsql=N'update cw_bookmark set Bookmark.modify(''declare namespace x="http://www.hellocw.com/onlinebookmark"; insert '+ @Insertcontent+' as last into (//x:Folder[@Id="'+@FolderId+'"])[1]'') where userId='''+@userID+''''; exec sp_executesql @contentsql;
View 2 Replies
View Related
Dec 19, 2005
Problem about pass a big string (over 8000 characters) to a variable nvarchar(max) in stored procedure in SQL 2005!
I know that SQL 2005 define a new field nvarchar(max) which can stored 2G size string.
I have made a stored procedure Hellocw_ImportBookmark, but when I pass a big string to @Insertcontent , the stored procedure can't be launch! why?
----------------------13-------------------------------------
create procedure Hellocw_ImportBookmark
@userId varchar(80),
@FolderId varchar(80),
@Insertcontent nvarchar(max)
as
declare @contentsql nvarchar(max);
set @contentsql=N'update cw_bookmark set Bookmark.modify(''declare namespace x="http://www.hellocw.com/onlinebookmark"; insert '+
@Insertcontent+' as last into (//x:Folder[@Id="'+@FolderId+'"])[1]'') where userId='''+@userID+'''';
exec sp_executesql @contentsql;
View 6 Replies
View Related
Jan 19, 2008
Hi,
My company is starting to use nvarchar columns in our database products. We just found out that, suppose table T1 has a my_nvarchar_col column, and there is a row containing a unicode text say "some Chinese", if you want to select that row, you have to append "N" in front of the unicode constant in the "WHERE" clause. That is:
select * from T1
where my_nvarchar_col = N'some Chinese'
will return that row, while
select * from T1
where my_nvarchar_col = 'some Chinese'
will return NOTHING.
This brings us a huge problem - we have tens of thousands of such queries in our existing PowerBuilder code base. Do we have to go through all of them to add "N" to the "WHERE" clause? Is there a way we can set some attribute of SQL Server so that we do not need to do that?
Project stalled and I am under extreme pressure so please help ASAP!!
View 1 Replies
View Related
Jan 25, 2007
Users can approach their userprofile on my site using: www.mysite.com/name=peterName is a unique value within my database (db type: nvarchar(50))Now, I have created a clustered index on the username column.However, IMHO its faster to create a clustered index on the (also unique) usercode column since that is of type int.BUT since a user can approach my site based on username I feel that I HAVE to live with this setback in performance....Is that true or is there a better way to solve this issue?
View 1 Replies
View Related