Escaping a whole string variable in T-SQL
Hi,
is it possible to escape o whole string variable in T-SQL like it is possible in PowerShell?
In PowerShell it works like this:
$PSstring = @'
Text with single quotes like ' or double quotes " or even an & or %.
And new line.
Any chance to escape it in T-SQL like in PowerShell above?
Regards,
Stefan
www.sc-orchestrator.eu ,
Blog sc-orchestrator.eu
Pretty sure the OP wants to escape the variable name itself to have a variable called
Text with single quotes like ' or double quotes " or even an & or %.
And new line.
Don't forget to mark helpful posts, and answers. It helps others to find relevant posts to the same question.
Similar Messages
-
Can I preserve carriage returns in a string variable from SQL Server?
I have an OLE data source that pulls data from sql server via a SELECT query. One of the fields is an NVARCHAR(max) which goes into a string variable which is later used in an expression. I am noticing that in the expression, carriage returns
/ line breaks in this field are being lost. Does anyone know how I can preserve these in the expression?Thanks everyone for the suggestions. I am certain there are both \r and \n in the database as when I print the field and then copy/paste to textedit to show the hidden characters, I can see both the CR and LF's.
I have implemented a workaround that is by no means elegant, but it gets the job done.
I found that \r and \n will evaluate in an expression but if they are part of another string variable, SSIS escapes them. My workaround was to change my OLE_DB select statement (which fetches the custom SQL query) to explicitly change the hidden characters
to '\r' and '\n' respectively:
SELECT REPLACE(REPLACE([CUSTOM_SQL],char(13),'\r'),char(10),'\n')
Then, in my SSIS expression, I de-escaped these characters:
REPLACE(REPLACE(@[User::vAlertCustomSQL],"\\r","\r"),"\\n","\n")
Now when the expression is executed, the SQL is formatted correctly and oddly placed comments in the query no longer break the query. -
Escape single quote from a String variable
Hi,
I have a String variable called "name" which i am using in my form tag.
<form name=test action="test.jsp?fname=<%=name%>" method="post">
But i am getting Javascript error if the "name" variable contains a string with some special characters like single quote( ' ).
Plz help me to escape this special char from my String variable.
Thanks..You need to url-encode the value using the URLEncoder class.
http://java.sun.com/javase/6/docs/api/java/net/URLEncoder.html
For example:
<form name=test action="test.jsp?fname=<%=URLEncoder.encode(name, "ISO-8859-1")%>" method="post"> -
How to get prepared string before sending to sql
Hi
I want the prepared string before sending to Sql (After substitution and setXXX), is it possible to do this? if yes, how ?
PreparedStatement ps = cn.prepareStatement("select * from table1 where name= ''?'' ");
ps.setString(1, "mytable")
<-- I want the prepared string before sending to Sql (After substitution and setXXX) -->
ResultSet rs = ps.executeQuery();
Thanks
AliAs I mentioned, I want Sql Text before execution
n (getting resultSet), and after whole of setXXXs,No way, I believe.
I have tried in many ways, let me put down my work.
String query = "'Select * from dept where deptno=?'";
System.out.println("Before : "+query);
PreparedStatement ps = con.prepareStatement("select "+query+",? from Dual");
ps.setInt(1,50);
ResultSet rs = ps.executeQuery();
if(rs.next()) {
System.out.println("After : "+rs.getString(1));
ps.close();
con.close();I have tried in these lines, to capture the sql query, but it is failing at execution and the exception is 'bind variable not found'. So, I think you need to implement your own class to construct this query. Getting the details from DatabaseMetadata to see how the driver's setter methods works and you can use the same logic in your custom class.
Good luck. -
How do I pass single quotes into a string variable?
Thanks for any help?
Example
Select xdat, yday
from foo
where
xdat = to_char(sysdate, 'mm/dd/yyyy')
How do I pass the single quoted stuff above into a string variable?Thank you but that is not the same thing. I am building a dynamic sql statement and need to pass the quoted material into a statement that is quoted Is that not what my example above shows?
My example above has a quoted string inside a string. I think this is exactly what you were asking for. -
Problem returning variables from dynamic SQL/PLSQL
Hi, I have a problem I am trying to solve using a very short piece of dynamic SQL or PLSQL but I am having problems getting the variable values out of the dynamic block.
I have 16 counters whose names are made up of three variable parts - 'scheme', 'contributory category' and 'employment category'
The 'scheme' can be either 'no1', 'no2', 'off', 'cg' or 'amc'
The 'contributory category' can be either 'cont' or 'noncont'
The 'employment category' can be either 'ft' or 'pt'
(There are only 16 because only 16 combinations are possible)
For example the total counter name could be 'v_cg_noncont_ft_count'
I have created a variable by concatenating the various elements called v_incr_count_name which holds the name of the counter I want to increment.
I am running this whole thing within an anonymous PLSQL block so I cannot use global variables meaning that my variables are not visible within a dynamic PLSQL block.
I believe this means that either I need to bind the variables within a PLSQL block or use a SELECT FROM INTO SQL block.
I have tried a few solutions with no luck such as the following PLSQL:
v_incr_count := 'v_'||v_scheme||'_'||v_cont_cat||'_'||v_emp_cat||'_count';
sql_stmt := 'BEGIN :a := :a + 1; END;';
EXECUTE IMMEDIATE sql_stmt USING v_incr_count_name;
Unfortunately I am getting the 'IN bind variable bound to an OUT position' error which I believe is because it is trying to return a value into v_incr_count_name which has been defined by default as an IN variable. The problem is that I need to store the returned value into the variable whose name is stored in v_incr_count_name.
Another solution I tried is:
v_incr_count_name := 'v_'||v_scheme||'_'||v_cont_cat||'_'||v_emp_cat||'_count';
sql_stmt := 'SELECT '||v_incr_count_name||' + 1 FROM DUAL';
EXECUTE IMMEDIATE sql_stmt INTO v_return;
This solution gives me an 'Invalid colum error'
Any help would be greatly appreciated
Cheers, DanRepost:
Problem with variables in dynamic SQL/PLSQL -
How i pass table column value to string variable or return to java applete
Hi Master,
How do I pass a table column value into string variable. See my code below:
import java.sql.*;
public class Waheed {
public Waheed() {
public static void main (String args [])
String s = "9 23 45.4 56.7";
System.out.println ("going for connection");
// DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn =
DriverManager.getConnection("jdbc:oracle:thin:@fahim:1521:aamir","muhammad","mfa786");
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery("select accid from accbal");
System.out.println ("going for connection");
while (rset.next())
s= rset.getString("accid"); this line give me error
System.out.println (rset.getString("accid"));
System.out.println (s);
catch(Exception e){
e.printStackTrace();
This line give me an error:
s= rset.getString("accid");
s is string variable
Plese give me an idea how I can pass accid in s variable.
Thanks.
AamirSee the code sample in the following thread (try using upeercase).
JDBC connection
Kuassi -
Pass a variable value to SQL Command in OLEDB Source
Hi,
I have the OLEdb Source where it has SQL Command as Data Access Mode. Below is the sample query that i have in that.
DECLARE @MonthOffSet int = 24
DECLARE @PaidDate_SK_Low datetime = dateadd(mm,MONTH(getdate())-@MonthOffSet-1,dateadd(year,datediff(year,0,dateadd(YY,0,getdate())),0))
DECLARE @PaidDate_SK_High datetime = dateadd(dd,-1,dateadd(MM,@MonthOffSet,@PaidDate_SK_Low))
followed by select statement which has where clause.
Instead of hard code the value 24, i am trying to get the value from variable. I know there is a limitation to add the parameters only in where clause. Is there any work around or solution.But i need to use the first four lines of code in lot other packages which has different sql statement. But if i make whole query variable then i have a limitation on length 4000 char.
DECLARE @MonthOffSet int = 24
DECLARE @PaidDate_SK_Low
datetime = dateadd(mm,MONTH(getdate())-@MonthOffSet-1,dateadd(year,datediff(year,0,dateadd(YY,0,getdate())),0))
DECLARE @PaidDate_SK_High
datetime = dateadd(dd,-1,dateadd(MM,@MonthOffSet,@PaidDate_SK_Low))
in my select statement in where clause i am using date range between @PaidDate_SK_Low
datetime and @PaidDate_SK_High
datetime
Any suggestions -
Using a number variable in an SQL statement
Hi,
I am trying to use a variable in an sql statement and I have run into problems when the variable is a number. The following line of code works if the variable is a string but not if it is a number.
"SELECT TOP 1 UUT_STATUS FROM UNIT_UUT_RESULT WHERE UnitID = '" + Locals.LocalUnitID + "' ORDER BY START_DATE_TIME DESC"
Is there a difference in the use of the single and double quotes and the + sign for number variables?
Thanks
Stuart
Solved!
Go to Solution.Hi Stuart,
I am assuming that the UnitID is stored as a numeric in the database? If so, the proper SQL syntax for comparing with numerics should not use a single quote (or any quotes for that matter). The quotes are used only for strings.
So you would want to use:
"SELECT TOP 1 UUT_STATUS FROM UNIT_UUT_RESULT WHERE UnitID = " + Locals.LocalUnitID + " ORDER BY START_DATE_TIME DESC"
This is really more of an SQL question universal to all languages, not just TestStand.
Here is an excellent resource that you can consult:
http://www.w3schools.com/sql/sql_where.asp
Jervin Justin
NI TestStand Product Manager -
Reading a binary file to string variable does not populate correctly
Hi, I am new to Adobe Air/Flex and I'm trying to read a
binary file which also contains text in "cleartext". The problem
I'm having is that when I call FileStream.readUTFBytes method, only
the first 6 characters are showing up in my string variable
"contents" when I debug it in FlexBuilder or use a trace command
and debug it. I have also tried with other types of files but I
have a similar problem unless it's a non-binary file.
Am I doing something incorrectly or should I be reading a
binary file differently than the way I'm reading it currently?
The source code is shown below.
TIA,
Magnus
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="
http://www.adobe.com/2006/mxml"
layout="absolute">
<mx:Script>
<![CDATA[
import flash.filesystem.File;
private function readFiles():void{
var feedFile:File = File.userDirectory.resolvePath( "Local
Settings/Application Data/Microsoft/Feeds/AppScout~.feed-ms" );
var stream:FileStream = new FileStream();
stream.open( feedFile, FileMode.READ );
var contents:String =
stream.readUTFBytes(stream.bytesAvailable);
trace(contents);
stream.close();
]]>
</mx:Script>
<mx:Button x="121" y="66" label="Button"
click="readFiles()" />
</mx:WindowedApplication>It's difficult to tell what it is, it looks like a binary
pipe symbol but I can copy it from TextPad for example. Some of the
characters following it cannot be copied from TextPad which I
assume is because it's null. I can read the whole file in C#/.Net
and assign it to a string variable without any problems but perhaps
Air is somewhat limited to binary content. -
Naming an ArrayList using value from a String variable
I am trying to name an ArrayList the value of a String variable in this code:
public void addstudent(String name)
ArrayList //i need a name here// = new ArrayList();
I want to use the String //name// that will be used when the method is called. What do I do? I tried using:
ArrayList (String.valueOf(name)) = new ArrayList();
That didn't work.
Thanks in advance for any help.Its suppossed to allow the user to input the student's name, grades for 4 specific subjects. Then take that and organize the students by name alphabetically. It is also suppossed to allow the user to search for users by grades, like find everybody with a GPA of 3.7 or higher or find everybody with a GPA of 3.5. This was a project asigned by my intro computer science teacher. I was suppossed to make it with 2D arrays but that was lousy because you were then limited to a specific number of students without editing the code. I'm not familiar with all the different ways of doing this. My computer science teacher said that I could do it with a HashSet.
Okay. You have a String. Let's suppose it contains "fred" or something like that -- you didn't say what was in it so we have to speculate. Next, you want to create an ArrayList from that? What does that mean? You want to end up with an ArrayList that contains one entry, that string? Or what?
In your example I would want to start by giving the method "fred" as the name parameter. So right now the String (name) has the value of "fred". I then wanted to make an ArrayList for that student named fred. This ArrayList would have 4 grades for that student fred. This ArrayList for fred would be part of a HashSet for the whole group of students. That way when I wanted to search alphabetically, I would just sort the HashSet. My computer science teacher said this would work.
Thanks -
Hi,
I am creating a Project Server Workflow (site workflow) using Visual Studio 2012.
If i set the "EnterProjectStage" activity with a GUID within quotes the workflow works
(as suggested in the MSDN blog (http://blogs.msdn.com/b/project_programmability/archive/2012/11/07/creating-project-workflows-using-visual-studio-2012.aspx).
However, the GUID of stages will change from environment to environmet (QA, Stage, PROD). So, I tried setting the GUID in a string variable (which i am populating dynamically) and assigned the string variable to the "EnterProjectStage"
activity. However, this dynamic assignment of stage id to "EnterProjectStage" does not work and after deployment the workflow dumps with the following error:
===============================================
Exception Starting Workflow: Sequence contains no elements. Trace: at System.Linq.Enumerable.First[TSource](IEnumerable`1 source) at Microsoft.Office.Project.Server.BusinessLayer.Workflow.<FillWorkflowStatusTableFromXaml>b__47(XElement
e) at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext() at System.Linq.Enumerable.<DistinctIterator>d__81`1.MoveNext() at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1
source) at Microsoft.Office.Project.Server.BusinessLayer.Workflow.FillWorkflowStatusTableFromXaml(String xaml, WorkflowDataSet& ds, Guid projUid) at Microsoft.Office.Project.Server.BusinessLayer.Workflow.StartWorkflow(Guid projectGuid, Guid enterpriseProjectTypeUid,
Boolean isNewProject, Guid previousEntepriseProjectTypeUid, Boolean skipStage, Guid stageToSkipTo):
WorkflowExceptionStartingWorkflow (35115). Details: id='35115' name='WorkflowExceptionStartingWorkflow'
uid='b31d825e-1d00-e411-9466-005056b11412'.
===============================================
Is there a way the "EnterProjectStage" can be made dynamic so that it reads from a variable.
Thanks,
Amitava.Arthur,
Thank you for your reply. But at this point, one of my points of confusion is what software I have available to me. I wish I had a useful central help desk to call up and just say, "Hey, load me up with all of the professional version(s) of Visual
Studio. But I do not know what we have license to. And I kind of need to know what the options are, so that I can ask a specific question of our vast buracracy.
For now, I have downloaded only free versions of Visual Studio client software. Since my company does have servers running Microsoft SQL Server, I am going to assume that we have proper licensing for those servers. But does that server license
allow me to get any professional versions of the PC client software for the various Visual Studio(s) 2012?
And if I get a professional version of Visual Studio 2012, does that do away with the three different flavors that I have right now? I have 2012 versions of SQL Server Management Studio, Visual Studio Express, and Visual Studio Shell (Integrated).
Your feedback is much appreciated.
Thanks! -
Using Variables in a SQL Statement
I know, I know, this is written in VB..I'm doing a VB Project right now for my Instructor (While in an Intermediate Java Class)
But VB (I feel) doesnt have very good support Forums.
Anyway, this is the problem:
I want to use String Variables to hold the place of field names in
a SQL Statement and the change the ORDER according to intCount's Loop:
The key word(s) here is "ORDER BY"
Private Sub DataGrid1_Click()
Dim intCount As Integer
Dim strColHead(11) As String
strColHead(0) = "RES__PUR_DT"
strColHead(1) = "VENDOR"
strColHead(2) = "VEN_LOC"
strColHead(3) = "RES_TYPE"
strColHead(4) = "RES_FROM_DT"
strColHead(5) = "RES_TO_DT"
strColHead(6) = "MISC_ADJ"
strColHead(7) = "STATE_TAX"
strColHead(8) = "LOC_CHARGE"
strColHead(9) = "RES_ID"
strColHead(10) = "RES_OP"
For intCount = 0 To 10
If DataGrid1.SelStartCol = intCount Then
Adodc1.RecordSource = "Select * from tblReservation order by 'strColHead(intCount)'"
End If
Adodc1.Refresh
Next intCount
End SubI'm just wondering if anyone knows a work around so that I might be able to store a Table's FIELD name in a variable or an array[] so that I can do a query based on the decision of a loop without having to code 10 IF/ELSE statements.For instance, although the above code will not work, this code, although quite lengthy, does:
If DataGrid1.SelStartCol = 0 Then
Adodc1.RecordSource = "Select * from tblReservation order by RES__PUR_DT"
Adodc1.Refresh
ElseIf DataGrid1.SelStartCol = 1 Then
Adodc1.RecordSource = "Select * from tblReservation order by VENDOR"
Adodc1.Refresh
ElseIf DataGrid1.SelStartCol = 2 Then
Adodc1.RecordSource = "Select * from tblReservation order by VEN_LOC"
Adodc1.Refresh
ElseIf DataGrid1.SelStartCol = 3 Then
Adodc1.RecordSource = "Select * from tblReservation order by RES_TYPE"
Adodc1.Refresh
ElseIf DataGrid1.SelStartCol = 4 Then
Adodc1.RecordSource = "Select * from tblReservation order by RES_FROM_DT"
Adodc1.Refresh
ElseIf DataGrid1.SelStartCol = 5 Then
Adodc1.RecordSource = "Select * from tblReservation order by RES_TO_DT"
Adodc1.Refresh
ElseIf DataGrid1.SelStartCol = 6 Then
Adodc1.RecordSource = "Select * from tblReservation order by MISC_ADJ"
Adodc1.Refresh
ElseIf DataGrid1.SelStartCol = 7 Then
Adodc1.RecordSource = "Select * from tblReservation order by STATE_TAX"
Adodc1.Refresh
ElseIf DataGrid1.SelStartCol = 8 Then
Adodc1.RecordSource = "Select * from tblReservation order by LOC_CHARGE"
Adodc1.Refresh
ElseIf DataGrid1.SelStartCol = 9 Then
Adodc1.RecordSource = "Select * from tblReservation order by RES_ID"
Adodc1.Refresh
ElseIf DataGrid1.SelStartCol = 10 Then
Adodc1.RecordSource = "Select * from tblReservation order by RES_OP"
Adodc1.Refresh
End If
Do you see where i'm going with this?
I simple want to use a variable in the "select * from <Table> Order by <Field>" -
Regular Expressions and String variables
Hi,
I am attempting to implement a system for searching text files for regular expression matches (similar to something like TextPad, etc.).
Looking at the regular expression API, it appears that you can only match using string variables. I just wanted to make sure this is true. Some of these files might be large and I feel uneasy about loading them into ginormous Strings. Is this the only way to do it? Can I make a String as big as I want?
Thanks,
-MikeNewlines are only a problem if you're reading the
text line-by-line and applying the regexp to each
line. It wouldn't catch expressions that span
lines.
@sabre150: your note re: CharSequence -- so what
you're suggesting is to implement a CharSequence that
wraps the file contents, and then use the regexps on
the whole thing? I like the idea but it seems like
it would only be easy to implement if the file uses a
fixed-width character set. Or am I missing
something...?You are correct for the most basic implementation. It is very easy to create a char sequence for fixed width character sets using RandomAccessFile. Once you go to character sets such as UTF-8 then more effort is required.
While ever the regex is moving forward thought the CharSequence one char at a time there is no problem because one can wrap a Reader but once it backtracks then one needs random access and one will need to have a buffer. I have used a ring buffer for this which seems to work OK but of course this will not allow the regex to move to any point in the CharSequence.
'uncle_alice' is the regex king round here so listen to him.
:-( I should read further ahead next time!
Message was edited by:
sabre150
Message was edited by:
sabre150 -
Comma problem with global string variable
Hi,
I'm fiighting with comma problem for global string variable. I've on page string for example "7nndqrr52vzyb,0" and by dynamic column link I'm assigning this string to global variable. Then I'm trying to display value of that global variable on another page but I see only string till comma, nothings more. I'm not sure what I'm doing wrong because when I'm trying to assign that value normally by computation process as a constant value is fine and see on another page correct string. I'll be really glad for help.
Thanks
Cheers,
MariuszWhen it tries to display the string, it sees the comma and wants to believe the string is terminated. You could escape the , in the string or replace it with a different character..
See this link: http://download.oracle.com/docs/cd/E17556_01/doc/user.40/e15517/concept.htm#BEIGDEHF
Thank you,
Tony Miller
Webster, TX
If vegetable oil is made of vegetables, what is baby oil made of?
If this question is answered, please mark the thread as closed and assign points where earned..
Maybe you are looking for
-
I need some assistance on stopping my backspace key from "sticking" on my iPad 2?
I have reset, restored, and rebooted. Nothing is working. My backspace key goes rogue even if I only hit it once. I've had this pad for 3 days and I'm a bit frustrated. I've noticed that the backspace key goes haywire in almost all third party apps b
-
Upgrading to V4 has lost all of my Bookmarks, I still have the restore files in my profile data but they will not load, I have tried importing the html backup file too but it didn't work either. How can I get them back?
-
Error editing data file, unable to load Region Definition
Hello I'm getting a parseException when I try to edit a data file from UCM. The steps followed are: 1- Create an element definition at Site Studio 2 - Create a Region Definition refering to the Element Definition 3 - Create a Content i
-
Missing component of Dreamweaver
I have been using Dreamweaver for a long time without any problems, now, reinstalling Windows XP and Dreamweaver after a breakdown I suddently face an annoying problem. When I try to insert a Flash Button into the page I get the following error messa
-
How to add search help to vbkd-inco2?
Hello All, I have a requirement to have drop down or f4 help with certain values to field VBKD-INCO2 while VA01/VA02. One way is add search help VBKD-INCO2 but it requires to change the standard table which require access key.. Please lemme know in d