OPENQUERY With Quotes In The Query String
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
ADVERTISEMENT
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
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
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
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
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
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
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
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
Jan 17, 2007
Help, please.
I'm going crazy trying to figure out how to form this SQL query. I am querying an Informix linked server and I need to pass a variable date. I am using an expression to create the query like so
"Select count(*) from " + @[User::varDBName] + ":informix.doc_tl WHERE " + @[User::varDBName] +":informix.doc_tl.d_received = {D " + @[User::varDate] +"} "
The informix query needs the date to be {D "2007-01-15"} but for the life of me, I can't get the date enclosed in quotes.
The error I get is
An OLE DB record is available. Source: "(null)". HResult: 0x80040E14
Description: "(null)"
Can anyone tell me what I'm doing wrong?
Thanks
View 3 Replies
View Related
Apr 18, 2008
Hi,
i have a query like
select * from table1 where @variable1
and variable1 id holding the value id=1
so what i want is select * from table1 where id=1
but here the values variable1 is passesed from a c# program which encloses the vaule within single quotes.
so what i get is select * from table1 where 'id=1'
how to correct this?
hope my question is clear.
Thanks
View 5 Replies
View Related
Feb 7, 2008
Hi,
I have a parameterized query. The parameters contain data from my tables. Some of the parameters could include single quotes. The single quotes are wreaking havoc in my parameterized query. How can I replace single quotes with double quotes inside of my SQL stored
procedure?
I know that it's something similar to REPLACE(@variablename, '''''', ''''''''), but I can't get the number of quotes right.
All of the examples that I am seeing are converting the quotes inside of an application. This is not an option for me, as I am calling this stored procedure from a SQL job that will run daily.
Thx.
View 2 Replies
View Related
Jul 23, 2005
I'm trying to pass through a SQL statement to an Oracle database usingOPENROWSET. My problem is that I'm not sure of the exact syntax I needto use when the SQL statement itself contains single quotes.Unfortunately, OPENROWSET doesn't allow me to use parameters so I can'tget around the problem by assigning the SQL statement to a parameter oftype varchar or nvarchar as inSELECT *FROM OPENROWSET('MSDAORA','myconnection';'myusername';' mypassword',@chvSQL)I tried doubling the single quotes as inSELECT *FROM OPENROWSET('MSDAORA','myconnection';'myusername';' mypassword','SELECT *FROM AWHERE DateCol > To_Date(''2002-12-01'', ''yyyy-mm-dd'')')But that didn't work. Is there a way out of this?Thanks,Bill E.Hollywood, FL
View 1 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
Mar 30, 2004
Hi,
in
OPENQUERY ( linked_server , 'query' )
is any size limit to 'query'
Thank you
Alex
View 1 Replies
View Related
May 19, 2008
Hi All, I am facing quotes problem. Without using the quotes
my query is running fine, but I need to use IIF condition so for that I
need quotes adjustment. I didn't figured it out how to adjust them, try
several techniques but no success. I am using dotnetnuke. {IIF,"[frmradio,form]=text"," SELECT Docs.FileName, Dept_LegalLaw.MediaID, Dept_LegalLaw.ID, Dept_LegalLaw.LevelID, Dept_LegalLaw.LawID, Dept_LegalLaw.LawDate, Dept_LegalLaw.Agreement, Dept_LegalLaw.Name, Dept_LegalLaw.NameSearch, Dept_LegalLawType.LawType, Dept_LegalLaw.LawNo, Dept_LegalMinistries.RegID, Dept_LegalLaw.IssueNo, Dept_LegalLaw.Attachment, Dept_LegalLaw.Amendment, Dept_LegalLaw.Scanned, Dept_LegalLaw.Html, Dept_LegalMinistries.Description FROM OPENQUERY(LEGALDBSERVER, 'SELECT Filename FROM SCOPE() WHERE Contains('" @FilterAnyWrd ")' ) AS Docs INNER JOIN Dept_LegalLaw ON Docs.FileName = Dept_LegalLaw.FileName INNER JOIN Dept_LegalMinistries ON Dept_LegalLaw.RegID = Dept_LegalMinistries.RegID INNER JOIN Dept_LegalLawType ON Dept_LegalLaw.LawID = Dept_LegalLawType.LawID ", " "} {IIF,"'[frmradio,form]'='title'"," SELECT MediaID, Dept_LegalLaw.ID, Dept_LegalLaw.LevelID, Dept_LegalLaw.LawID, LawDate, Agreement, Name, NameSearch, Dept_LegalLawType.LawType, LawNo, Dept_LegalMinistries.RegID, IssueNo, Attachment, Amendment, Scanned, Html, Dept_LegalMinistries.Description, Dept_LegalLaw.FileName FROM Dept_LegalLaw LEFT JOIN Dept_LegalMinistries ON Dept_LegalLaw.RegID COLLATE DATABASE_DEFAULT = Dept_LegalMinistries.RegID COLLATE DATABASE_DEFAULT INNER JOIN Dept_LegalLawType ON Dept_LegalLaw.LawID COLLATE DATABASE_DEFAULT = Dept_LegalLawType.LawID COLLATE DATABASE_DEFAULT WHERE @FilterLawNo AND @FilterLawID AND @FilterRegID AND @FilterIssueNo AND @FilterFromDate AND @FilterToDate AND @FilterNtContNew AND @FilterAgreement AND @FilterAllWrdNew AND @FilterExWrdNew AND @FilterAnyWrdNew ORDER BY [SORTTAG] ", " "} Thanks for any help
View 2 Replies
View Related
Oct 10, 2007
Does anyone know why this statement would fail? I have created my own assembly which is on the server and when i run the mdx query call myassembly.mystoredproc() it returns data, but now when I use call myassembly.mystoredproc() it returns an error.
using an mdx query this works fine
call AsmTest.Asm.Analysis.TestClass.NameMe()
When using openquery i get an error
select * from openquery(NV, 'call AsmTest.Asm.Analysis.TestClass.NameMe()' )
OLE DB provider "MSOLAP.3" for linked server "NV" returned message "Prepare is not safe during execution of the NameMe stored procedure.".
Msg 7321, Level 16, State 2, Line 1
An error occurred while preparing the query "call AsmTest.Asm.Analysis.TestClass.NameMe()" for execution against OLE DB provider "MSOLAP.3" for linked server "NV".
linked server definition
USE master
GO
/* Add new linked server */
EXEC sp_addlinkedserver
@server='NV', -- local SQL name given to the linked server
@srvproduct='', -- not used
@provider='MSOLAP.3', -- OLE DB provider (the .2 means the SQL2K version)
@datasrc='nvsifwfp', -- analysis server name (machine name)
@catalog='ARTSDW' -- default catalog/database
View 1 Replies
View Related
May 22, 2007
Hello to all,
I have a problem with ms sql query. I hope that somebody can help me.
i have a table "Relationships". There are two Fields (IDMember und RelationshipIDs) in this table. IDMember is the Owner ID (type: integer) und RelationshipIDs saves all partners of this Owner ( type: varchar(1000)). Example Datas for Table Relationships: IDMember Relationships .
3387 (2345, 2388,4567,....)
4567 (8990, 7865, 3387...)
i wirte a query to check if there is Relationship between two members.
Query:
Declare @IDM int; Declare @IDO int; Set @IDM = 3387, @IDO = 4567;
select *
from Relationship where (IDMember = @IDM) and ( cast(@ID0 as char(100)) in
(select Relationship .[RelationshipIDs] from Relationship where IDMember = @IDM))
But I get nothing by this query.
Can Someone tell me where is the problem? Thanks
Best Regards
Pinsha
View 9 Replies
View Related
Feb 13, 2006
We have the following two tables :
Link ( GroupID int , MemberID int )
Member ( MemberID int , MemberName varchar(50), GroupID varchar(255) )
The Link table contains the records showing which Member is in which Group. One particular Member can be in
multiple Groups and also a particular Group may have multiple Members.
The Member table contains the Member's ID, Member's Name, and a Group ID field (that will contains comma-separated
Groups ID, showing in which Groups the particular Member is in).
We have the Link table ready, and the Member table' with first two fields is also ready. What we have to do now is to
fill the GroupID field of the Member table, from the Link Table.
For instance,
Read all the GroupID field from the Link table against a MemberID, make a comma-separated string of the GroupID,
then update the GroupID field of the corresponding Member in the Member table.
Please help me with a sql query or procedures that will do this job. I am using SQL SERVER 2000.
View 1 Replies
View Related
Mar 25, 2008
Hi all,
In the Programmability/Stored Procedure of Northwind Database in my SQL Server Management Studio Express (SSMSE), I have the following sql:
USE [Northwind]
GO
/****** Object: StoredProcedure [dbo].[SalesByCategory] Script Date: 03/25/2008 08:31:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SalesByCategory]
@CategoryName nvarchar(15), @OrdYear nvarchar(4) = '1998'
AS
IF @OrdYear != '1996' AND @OrdYear != '1997' AND @OrdYear != '1998'
BEGIN
SELECT @OrdYear = '1998'
END
SELECT ProductName,
TotalPurchase=ROUND(SUM(CONVERT(decimal(14,2), OD.Quantity * (1-OD.Discount) * OD.UnitPrice)), 0)
FROM [Order Details] OD, Orders O, Products P, Categories C
WHERE OD.OrderID = O.OrderID
AND OD.ProductID = P.ProductID
AND P.CategoryID = C.CategoryID
AND C.CategoryName = @CategoryName
AND SUBSTRING(CONVERT(nvarchar(22), O.OrderDate, 111), 1, 4) = @OrdYear
GROUP BY ProductName
ORDER BY ProductName
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
From an ADO.NET 2.0 book, I copied the code of ConnectionPoolingForm to my VB 2005 Express. The following is part of the code:
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.Common
Imports System.Diagnostics
Public Class ConnectionPoolingForm
Dim _ProviderFactory As DbProviderFactory = SqlClientFactory.Instance
Public Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
'Force app to be available for SqlClient perf counting
Using cn As New SqlConnection()
End Using
InitializeMinSize()
InitializePerfCounters()
End Sub
Sub InitializeMinSize()
Me.MinimumSize = Me.Size
End Sub
Dim _SelectedConnection As DbConnection = Nothing
Sub lstConnections_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lstConnections.SelectedIndexChanged
_SelectedConnection = DirectCast(lstConnections.SelectedItem, DbConnection)
EnableOrDisableButtons(_SelectedConnection)
End Sub
Sub DisableAllButtons()
btnAdd.Enabled = False
btnOpen.Enabled = False
btnQuery.Enabled = False
btnClose.Enabled = False
btnRemove.Enabled = False
btnClearPool.Enabled = False
btnClearAllPools.Enabled = False
End Sub
Sub EnableOrDisableButtons(ByVal cn As DbConnection)
btnAdd.Enabled = True
If cn Is Nothing Then
btnOpen.Enabled = False
btnQuery.Enabled = False
btnClose.Enabled = False
btnRemove.Enabled = False
btnClearPool.Enabled = False
Else
Dim connectionState As ConnectionState = cn.State
btnOpen.Enabled = (connectionState = connectionState.Closed)
btnQuery.Enabled = (connectionState = connectionState.Open)
btnClose.Enabled = btnQuery.Enabled
btnRemove.Enabled = True
If Not (TryCast(cn, SqlConnection) Is Nothing) Then
btnClearPool.Enabled = True
End If
End If
btnClearAllPools.Enabled = True
End Sub
Sub StartWaitUI()
Me.Cursor = Cursors.WaitCursor
DisableAllButtons()
End Sub
Sub EndWaitUI()
Me.Cursor = Cursors.Default
EnableOrDisableButtons(_SelectedConnection)
End Sub
Sub SetStatus(ByVal NewStatus As String)
RefreshPerfCounters()
Me.statusStrip.Items(0).Text = NewStatus
End Sub
Sub btnConnectionString_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnConnectionString.Click
Dim strConn As String = txtConnectionString.Text
Dim bldr As DbConnectionStringBuilder = _ProviderFactory.CreateConnectionStringBuilder()
Try
bldr.ConnectionString = strConn
Catch ex As Exception
MessageBox.Show(ex.Message, "Invalid connection string for " + bldr.GetType().Name, MessageBoxButtons.OK, MessageBoxIcon.Error)
Return
End Try
Dim dlg As New ConnectionStringBuilderDialog()
If dlg.EditConnectionString(_ProviderFactory, bldr) = System.Windows.Forms.DialogResult.OK Then
txtConnectionString.Text = dlg.ConnectionString
SetStatus("Ready")
Else
SetStatus("Operation cancelled")
End If
End Sub
Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAdd.Click
Dim blnError As Boolean = False
Dim strErrorMessage As String = ""
Dim strErrorCaption As String = "Connection attempt failed"
StartWaitUI()
Try
Dim cn As DbConnection = _ProviderFactory.CreateConnection()
cn.ConnectionString = txtConnectionString.Text
cn.Open()
lstConnections.SelectedIndex = lstConnections.Items.Add(cn)
Catch ex As Exception
blnError = True
strErrorMessage = ex.Message
End Try
EndWaitUI()
If blnError Then
SetStatus(strErrorCaption)
MessageBox.Show(strErrorMessage, strErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
SetStatus("Connection opened succesfully")
End If
End Sub
Sub btnOpen_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnOpen.Click
StartWaitUI()
Try
_SelectedConnection.Open()
EnableOrDisableButtons(_SelectedConnection)
SetStatus("Connection opened succesfully")
EndWaitUI()
Catch ex As Exception
EndWaitUI()
Dim strErrorCaption As String = "Connection attempt failed"
SetStatus(strErrorCaption)
MessageBox.Show(ex.Message, strErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Sub btnQuery_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnQuery.Click
Dim queryDialog As New QueryDialog()
If queryDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Me.Cursor = Cursors.WaitCursor
DisableAllButtons()
Try
Dim cmd As DbCommand = _SelectedConnection.CreateCommand()
cmd.CommandText = queryDialog.txtQuery.Text
Using rdr As DbDataReader = cmd.ExecuteReader()
If rdr.HasRows Then
Dim resultsForm As New QueryResultsForm()
resultsForm.ShowResults(cmd.CommandText, rdr)
SetStatus(String.Format("Query returned {0} row(s)", resultsForm.RowsReturned))
Else
SetStatus(String.Format("Query affected {0} row(s)", rdr.RecordsAffected))
End If
Me.Cursor = Cursors.Default
EnableOrDisableButtons(_SelectedConnection)
End Using
Catch ex As Exception
Me.Cursor = Cursors.Default
EnableOrDisableButtons(_SelectedConnection)
Dim strErrorCaption As String = "Query attempt failed"
SetStatus(strErrorCaption)
MessageBox.Show(ex.Message, strErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Else
SetStatus("Operation cancelled")
End If
End Sub
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
I executed the code successfully and I got a box which asked for "Enter the query string".
I typed in the following: EXEC dbo.SalesByCategory @Seafood. I got the following box: Query attempt failed. Must declare the scalar variable "@Seafood". I am learning how to enter the string for the "SQL query programed in the subQuery_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnQuery.Click" (see the code statements listed above). Please help and tell me what I missed and what I should put into the query string to get the information of the "Seafood" category out.
Thanks in advance,
Scott Chang
View 4 Replies
View Related
Apr 5, 2005
below is the code of my sp
it's giving my wrong result: 1 instead 0 and vice versa
could you please check what's wrong with it: i think there is something related to @var2 in the code colored in orange.
Thanks!
Code:
ALTER PROCEDURE sp_name
(
@param1 int = NULL,
@param2 int = NULL,
@Result int OUTPUT
)
AS
DECLARE @var1 AS varchar(255)
DECLARE @var2 AS varchar(255)
DECLARE @x AS varchar(1000)
IF @param1 IS NOT NULL
BEGIN
SET @var1 = (
SELECT t1col1
FROM tabl1
WHERE t1col2 = @param1)
SET @var2 = ''
DECLARE crsr CURSOR FOR
SELECT t2col1 FROM tabl2 WHERE t2col2 = @var1
OPEN crsr
FETCH NEXT FROM crsr INTO @x
WHILE @@FETCH_STATUS = 0
BEGIN
SET @var2 = @var2 + '''' + @x + '''' + ', '
FETCH NEXT FROM crsr INTO @x
END
CLOSE crsr
DEALLOCATE crsr
SET @var2 = SUBSTRING(@var2, 1, LEN(@var2) - 1)
END
ELSE
BEGIN
SET @var2 = (SELECT t2col1 FROM t2 WHERE tb2col3 = @param2)
SET @var2 = '''' + @var2 + ''''
END
PRINT @var2
IF EXISTS (SELECT * FROM tabl3 WHERE t3col1 IN (@var2))
OR
EXISTS (SELECT * FROM tabl4 WHERE t4col1 IN (@var2))
BEGIN
SET @Result = 1
END
ELSE
BEGIN
SET @Result = 0
END
View 1 Replies
View Related
Mar 19, 2008
Hi all,
How do you put quotes in quotes so it looks like this below?
exec('select IDENT_CURRENT('table')')
Not
exec('select IDENT_CURRENT('table')')
I just don't want the middle quotes to end the initial quote..
thanks in advance..
View 1 Replies
View Related
Jan 13, 2005
This is the sql statement I have:
Code:
select * from tblCalls where TNum = [NUMBER] and Street like '[TEXT]'
The problem is that the Street field contains street names with quotes (ex. DE L'ACADIE). When I run this query using this street name, it doesn't work because of the ' between the L and the A. How can I tell SQL to "ignore" the ' in the text?
View 9 Replies
View Related
Jul 25, 2007
Hi,
I am creating a flat file connection to a .csv file
In the columns section of the flatt file connection manager editor, I am not sure why the texts in the .csv file are shown with double quotes arouond them.
They do not have "" in the .csv file.
Thanks
View 1 Replies
View Related
Mar 23, 2007
Has previous work been done on this? Is their a library one can download? Here's the problem. In an aricle a person or author may make a statement about a subject or a person. I am making a database on this.
For example, here in Israel, PM Olmert may make a statement on the teacher's strike or on Abu Mazen. The article may say, speaking of Mazen, Olmert said such and such. PM Olmert said, "xxxxxxx......." with the previous material making it clear whathe was speaking of.
Right now I have ugly code. Is there a neat way of doing this?
If this is the wrong forum, can somebody direct me to the right forum?
Thanks.
Dennist
View 3 Replies
View Related
Sep 14, 2004
Hi All,
Does anyone know the syntax for an insert statement using Openquery in a stored procedure? All the examples I've seen are Select statements, but I want to send data to a linked server.
Would I be better off using DTS??
Thanks,
Greg
View 1 Replies
View Related
Dec 13, 2007
How to create linked server to Dbf,
How to openquery util step by step
View 1 Replies
View Related
Sep 19, 2007
HI,
Can we use OPENQUERY with a parameter? Something like this:
SELECT * FROM OPENQUERY(@SOURCE_SERVER_NAME, 'Select * from dbo.FEED')
Please let me know at the earliest. Thanks a lot,.
Mannu.
View 3 Replies
View Related
Jun 14, 2007
I have got a grid view which i want to query i have added a WHERE for it WHERE (([carinfo] = @carinfo) AND ([carmake] = @carmake) AND ([postcode] LIKE '%' + @postcode + '%') AND ([carprice] <= @carprice)) I have made a search page with 4 textboxes and a search button but what i cant same to get working is the code to take the infor from my text boxes and run the query on the grid view page.If i just had a query with (([carinfo] = @carinfo) i can get that to work by doing this Protected Sub SearchButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles searchButton.Click '~/Default2.aspx Response.Redirect("search.aspx?man=" + Carmake.Text) End Sub After that i just dont know what to do, my asp code for the Data Source is <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:addcar %>"
SelectCommand="SELECT [AdId], [carinfo], [carmake], [cartype], [carprice], [other1], [enginesize], [fuel], [listdate], [adtitle] FROM [classifieds_ex] WHERE (([carinfo] = @carinfo) AND ([carmake] = @carmake) AND ([postcode] LIKE '%' + @postcode + '%') AND ([carprice] <= @carprice))"> <SelectParameters> <asp:QueryStringParameter Name="carinfo" QueryStringField="man" Type="String" /> <asp:QueryStringParameter Name="carmake" QueryStringField="make" Type="String" /> <asp:QueryStringParameter Name="postcode" QueryStringField="postcode" Type="String" /> <asp:QueryStringParameter Name="carprice" QueryStringField="pricerange" Type="Decimal" /> </SelectParameters> if anyone could help me with this would be great i been trying to work this out for two days now. Keep safeNick
View 2 Replies
View Related
Dec 10, 2007
Hi,
I'm self learning asp.net and have a little experience in vb.net. What i'm trying to do is run an SQL query and write the results into variables. The SQL query's im running will only ever return 1 row (specifing primary key / uniqueID). This is becasue i dont want to output the results as a table, rather to other objects. (using VS Web Developer express 2008)
Currently my code is:
------------------------------------------------------------------------------------------------------------------------------------------------------
Imports System
Imports System.Data.SqlClientPartial Class details
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Dim VariablesDim job_id As Integer
Dim myConnection As SqlConnection
Dim var_jobid As String = ""
Dim var_2 As String = ""
Dim var_3 As String = ""Dim SQL_read As New Object
'Write valus to Variables
job_id = Request.QueryString(job_id)SQL_read = "SELECT * FROM TABLE_NAME WHERE job_id = " & job_id
'Write Variables and Text to labelsLbl_title.Text = "Details for Job " & job_id
Lbl_jobid.Text = job_id
'Try to Establish link to SQL Server
'===================================
TrymyConnection = New SqlConnection("server= [my server here] ; database=ServerLog ; User Id = sa; Password= [my password here]")
myConnection.Open()
--------------------------------------------------------------------------------------------------------------------------------
I realise the quality of the code may be pretty abismal, due to pretty much guessing my way through. I dont know how to basically 'run' my sql query for starters, and then to output the results into variables. -IE- coloumn 1 (row1) of my results being put into var_1, column 2(row1) being put into var_2 etc etc.
Thanks in advance
Luke
View 3 Replies
View Related
Feb 4, 2008
I inherited a project at work in which I have to diagnose a bad query string that should be passing a value. Below are what I hope are relevant pieces of code. Your help ASAP will help insure job protection for yours truly. Thanks.
Dim strSQL as String = "SP2 "'strSQL = strSQL & Request.Cookies("ODM")("User_ID_NO") & ", "strSQL = strSQL & Request.Querystring("queue_id")strSQL = strSQL & ",'" & Request.Querystring("subtype")+ "'" ''xx no subtype is being passed herePart of SP2:SELECT
'<A target="new" href="../document-ds.aspx?dcn=' + CAST(A.DCN AS VARCHAR(25)) + '">' + CAST(A.DCN AS VARCHAR(25)) +
'</A>' AS 'DCN', QUEUE_NAME AS 'Queue Name', DOC_SUBTYPEDESC as 'Department' , DOC_CLASSDESC as 'WorkGroup',
DOC_TYPEDESC as 'Doc Type' , WKF_SUBMIT as 'Received Date', QI.QUEUE_DATE as 'Queue Date',
dbo.MIN2PARTS(DATEDIFF(mi,A.WKF_SUBMIT, GETDATE())) as 'Doc Age',
CASE
WHEN (DBO.SLA_HOURSDIFF_DCN(A.WKF_SUBMIT, GETDATE(), A.DCN) - SLA_HOURS) > 0 THEN
'<font color = red> ' + CAST(DBO.SLA_HOURSDIFF_FORMAT( DBO.SLA_HOURSDIFF_DCN
(A.WKF_SUBMIT, GETDATE(),A.DCN)) AS VARCHAR(25)) + '</font>'
WHEN (DBO.SLA_HOURSDIFF_DCN(A.WKF_SUBMIT, GETDATE(), A.DCN) - SLA_HOURS) < = 0 THEN
'<font size = 2 color = green><b> 0 </b></font>'
WHEN (DBO.SLA_HOURSDIFF_DCN(A.WKF_SUBMIT, GETDATE(), A.DCN) - SLA_HOURS) IS NULL THEN 'No SLA Configured'
END AS 'Out of SLA', (DBO.SLA_HOURSDIFF(A.WKF_SUBMIT, GETDATE()) -SLA_HOURS) as 'SLA_HOURS'
FROM
T_WF_DOC_TYPES DT
INNER JOIN T_WF_AP_TRACKING A ON A.DOC_ID = DT.DOC_ID
INNER JOIN T_WF_QUEUE_INV QI ON QI.DCN = A.DCN
INNER JOIN T_WF_QUEUES Q ON Q.QUEUE_ID = QI.QUEUE_ID
WHERE Q.QUEUE_ID = @QUEUE_ID
AND DT.DOC_SUBTYPE = @DOC_SUBTYPE
My main task is to discover where the @DOC_SUBTYPE comes from and why it's not passing the value to the stored proc or beyond. Let me know if you have any other questions since I'm unsure if I gave you the right info or not.
View 5 Replies
View Related
Apr 11, 2008
usa,united states - united states
usa,spain - spain
usa,france - france
how to get that?
View 4 Replies
View Related