开发者

Storing single quotes in varchar variable SQL Server 2008

开发者 https://www.devze.com 2023-04-12 09:45 出处:网络
I was wondering if there is a way to store single quote marks in SQL Server 2008.I am building several reports up and all these reports are the exact same, except they only differ in the codes I am se

I was wondering if there is a way to store single quote marks in SQL Server 2008. I am building several reports up and all these reports are the exact same, except they only differ in the codes I am selecting upon. For example, one report uses codes 'abc', 'def', 'ghi' and another report uses codes 'jkl', 'mno', 'pqr'. I was thinking to reduce the number of Stored Procedures I will have to make, I could make a parameter on the report to choose which ty开发者_StackOverflow社区pe of report to run. Based off of that, I would use the correct codes. So I was going to store these codes in a varchar variable. Below is the functionality I was hoping for:

DECLARE @codes1 varchar, @codes2 varchar
SET @codes1 = ''abc', 'def', 'ghi''
SET @codes2 = ''jkl', 'mno', 'pqr''

Then, I was going to use the proper varchar variable based on the parameter the user chooses. The only problem is setting the variables since the string will have single quotes in it (the string will be used in an SQL 'IN' statement, thats the reason for the single quotes being present).


Like this. Yes Oded is correct. The proper terminology for this is 'escaping'. You can escape a single quote ' by doubling it up ''

DECLARE @codes1 varchar(50), @codes2 varchar(50)
SET @codes1 = '''abc'', ''def'', ''ghi'''
SET @codes2 = '''jkl'', ''mno'', ''pqr'''


Try to avoid hard-coding values. Create a table to hold these values along with a way to group them.

Table CodeGroups
GroupNumber | Codes
       1    | abc
       1    | def
       1    | ghi
       2    | kkl
       2    | mno
       2    | pqr

This way the user only has to select GroupNumber = 1

You link the CodeGroups table to the table with the code strings. All you have to do to add another code is make an entry in this table and give it a group number.


Avoid single qoute problem just by doubling it.

Value Varchar2(10):= ''abc''; ---You will get error.

Value Varchare(10):= '''abc'''; ---Will Solve your problem.


                            int varId = "1";
                            String varItem = "Google's root";

                            String strSQL = "INSERT INTO table("
                                            + "id,"
                                            + "item"
                                            +")" 
                                            + "VALUES('" + varId 
                                            + "', '" + varItem
                                            + "')";
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号