Correct Syntax Using Variables Inside SQL Queries (SqlCommand)
Mar 30, 2008
I have a test page where I'm using SqlConnection and SqlCommand to update a simple database table (decrease a number).
I'm trying to figure out how to make a number in the database table to decrease by 1 each time a button is being pressed. I know how to update the number by whatever I want to, but I have no idea what the correct syntax is for putting variables inside the query etc. Like "count -1" for instance.
The database table is called "friday" and the one and only column is called "Tickets".
Here's the code behind the button:protected void Button1_Click(object sender, EventArgs e)
{SqlConnection conn;
conn = new SqlConnection("Data Source=***;Initial Catalog=***;Persist Security Info=True;User ID=***;Password=***");
conn.Open();int count = -1;
SqlCommand cmd = new SqlCommand("select Tickets from friday", conn);
count = (int)cmd.ExecuteScalar();if (count > 0)
{
string updateString = @"
update friday
set Tickets = 500" ; <------ Here I want to set Tickets like "current count -1"SqlCommand cmd2 = new SqlCommand(updateString);
cmd2.Connection = conn;
cmd2.ExecuteNonQuery();
}
else
{
}
conn.Close();
}
View 3 Replies
ADVERTISEMENT
May 20, 2008
Why does the following call to a stored procedure get me this error:
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'CONVERT'.
Code Snippet
EXECUTE OpenInvoiceItemSP_RAM CONVERT(DATETIME,'01-01-2008'), CONVERT(DATETIME,'04/30/2008') , 1,'81350'
The stored procedure accepts two datetime parameters, followed by an INT and a varchar(10) in that order.
I can't find anything wrong in the syntax for CONVERT or any nearby items.
Help me please. Thank you.
View 7 Replies
View Related
Sep 25, 2006
HelloI have having trouble displaying some simple columns in ascending order.I know that the database is populated and I can get the more complex code to work if I display like this: SELECT FName, LName, Town, '<a href="' + url + '">' + Site + '</a>' as LinkFROM Names_DBWHERE FName = 'Tom' And url like 'http:%'ORDER BY LName ASCBut I need a simpler view but I can't get it to workI have tried this:SELECT FName, LNameFROM Names_DBORDER BY LName ASCAnd thisSELECT FName, LNameFROM Names_DBORDER BY LName ASC; And This:SELECT FName, LNameFROM Names_DBORDER BY LName 'ASC' What is wrong with this syntax?ThanksLynn
View 2 Replies
View Related
Mar 15, 2007
I have a query and I need to check to see if a field is occupied, i.e., it can have anything in it, i just want to see if something is there... this is what I want, but of course, anything isn't the right word here...
and (r.id = 'anything')
View 7 Replies
View Related
Feb 25, 2008
Hi.
This is a Stored proc I am working on
I dont know much about stored procs.
This is what I am trying to achieve
The proc takes two input parameter and returns one outparameter.
This is what I have
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[GetNextAction]
(
@Code char(10),
@Track varchar(30),
@NextAction ntext output
)
AS
BEGIN
SET NOCOUNT ON;
Declare @ID int;
@ID = Select Sequence from [dbo].[Track] where Code=@Code;
Declare @nextCode varchar;
@nextCode= Select Code from [dbo].[Track] where sequence =(@ID+1);
@NextAction= Select nextAction from [dbo].[CaseStage] where Code=@nextCode;
return @NextAction;
END
GO
I guess you can understand what I am trying in the proc but the rules and syntax are wrong. Please help me with this.
Thanks
View 4 Replies
View Related
Dec 3, 2006
hi there
RS2005 - Layout tab
I have a field that says
txtTrackerTrue=Sum(Iif ((Fields!Tracker.Value = Fields!RecvdBy.Value), 1,0 ))
I want another field that says
txtAllTrue=Sum(Iif ((Fields!Tracker.Value, ClosedBy.Value = Fields!RecvdBy, 1,0 ))
obviously this is going to error
how would I do this please
thanks
View 19 Replies
View Related
Oct 19, 2007
select CONVERT(VARCHAR, stdate, 'YYYY') startyear
from tbl_emp
i want output : 2007
How can i get?
View 5 Replies
View Related
Jan 29, 2008
If someone can show me the correct syntax for the right side of the code below, I'd appreciate it.
srcMoreInfo.InsertParameters("Address").DefaultValue = DirectCast(cuwMoreInfo.FindControl("txtAddress"), TextBox).Text
View 11 Replies
View Related
Jun 21, 2000
CREATE PROCEDURE test1
@spname nvarchar(20),
@tblname nvarchar(50)
AS
declare @sqlrun varchar(8000)
set @sqlrun = "CREATE PROCEDURE @sp_name AS CREATE TABLE @tblname
(MsdsId [nvarchar] (5),
IngredId [nvarchar] (2),
Agency [nvarchar] (10),
AgencyText [nvarchar] (4) ,
nName [nvarchar] (40))"
eXEC sp_ExecuteSql @sqlrun
WHATS WRONG IN THIS CODE ?
---------------------------------
PS: I'm getting this error:
-------------------------------
Server: Msg 214, Level 16, State 2, Procedure sp_executesql, Line 7
Cannot convert parameter '@statement' to ntext/nchar/nvarchar data type expected by procedure.
View 2 Replies
View Related
Feb 27, 2007
Hi, I'm new to SQL and was wondering if there was an easier way to filter data.
I have two tables -
The first table called Names of Companies has a column named: NAMES
NAMES
XYZ Company
ABC Limited Liability Company
ZZZ Corporation
KKK Inc.
ABC Inc.
The second table called Keywords has a column named: WORDS
WORDS
Company
Limited
I want to search for all NAMES that contain the WORDS in some form
The results should be:
NAMES
XYZ Company
ABC Limited Liability Company
Technically, I can get the results I want by manually typing into the SQL statement all the words that appear in the WORDS column.
SELECT *
FROM [Names of Companies]
WHERE [Names of Companies].Names Like "*Company*" Or ([Names of Companies].Names) Like "*limited*"));
But is there a way that I reference the table Keyword instead of typing into the query statement all the words that appear in the column WORD? I have a lot of words to search for.
Can anyone recommend a better way to do this?
Thanks for all your help!
View 8 Replies
View Related
May 18, 2006
Somehow I'm not getting dtsrun to work.
The server is local
The name of the package is ImportHosttrncs. It is saved under Local Packages.
There is no password.
Is this syntax correct?
dtsrun /Slocalhost /PImportHosttrncs
View 1 Replies
View Related
Apr 11, 2008
What is the correct syntax for dropping a column if it exists?
Cant seem to get it to work. This is SQL 2005 if it makes a difference.
ALTER TABLE Reports_PI_Recent
IF EXISTS (DROP COLUMN RollingAverage )
View 3 Replies
View Related
Dec 30, 2007
I'm trying to create a SQL job in SQL Server and am a little unclear about the formatting.Here's a snippet from the stored procedure that creates the job:CREATE PROCEDURE [dbo].[spArchive] @DB varchar(30), @Date DateTimeAS EXEC msdb.dbo.sp_add_jobstep @job_name = 'ArchiveIncentives' , @step_id = 1 , @step_name = 'ArchiveAHD' , @subsystem = 'TSQL' , @command = 'spArchiveAHD ''@Date''' , @on_success_action = 3 , @on_fail_action = 2 , @database_name = '@DB' , @retry_attempts = 1 In this case, the job will be calling this stored procedure:CREATE PROCEDURE [dbo].[spArchiveAHD] ( @dtArchiveBefore DateTime)AS I'm unclear about these lines: @command = 'spArchiveAHD ''@Date''' @database_name = '@DB' Do they look correct to you or should I drop some/all of the apostrophes?Robert W.
View 5 Replies
View Related
Apr 3, 2008
I try to call the storeproc to perform task by allowing only input 6 of length. The syntax over here might not be relevant, im seeking for correct syntax.
webform
Dim connString2 As String = _ConfigurationManager.ConnectionStrings("Local_LAConnectionString1").ConnectionString Using myConnection2 As New SqlConnection(connString2)
Dim test01 As IntegerDim myPuzzleCmd2 As New SqlCommand("GetRandomCode", myConnection2)
myPuzzleCmd2.CommandType = CommandType.StoredProcedure
Dim retLengthParam As New SqlParameter("@Length", SqlDbType.TinyInt, , 6) < -------- allow 6 letters in length to be input
retLengthParam.Direction = ParameterDirection.InputmyPuzzleCmd2.Parameters.Add(retLengthParam) Dim retRandomCode As New SqlParameter("@RandomCode", SqlDbType.VarChar, 30)
retRandomCode.Direction = ParameterDirection.Output
myPuzzleCmd2.Parameters.Add(retRandomCode)
TryDim reader2 As SqlDataReader = myPuzzleCmd2.ExecuteReader()
myPuzzleCmd2.ExecuteNonQuery()
Catch ex As Exception Response.Write("sp value : " & retRandomCode.Value)
Dim iRandomCode(1) As StringReDim Preserve iRandomCode(1)
iRandomCode(1) = Convert.ToString(retRandomCode.Value)myPuzzleCmd2 = Nothing
Session.Remove("RandomCode") HttpContext.Current.Session("RandomCode") = iRandomCode(1) Response.Write(Session("RandomCode"))
Finally
myConnection2.Close()
End Try
End Using
StoredProcedure ALTER PROC [dbo].[GetRandomCode]
@Length TINYINT,
@RandomCode VARCHAR(30) OUTPUT
ASDECLARE
@Chars2BUsed VARCHAR(30),
@LookAt TINYINT,
@iCnt INT,
@CharFound CHAR(1)
SELECT @Chars2BUsed ='ABCDEFGHJKLMNPQRTUVWXYZ2346789'
SELECT @RandomCode = ''SELECT @iCnt = 1 WHILE @iCnt<=@Length
BEGINSELECT @LookAt = FLOOR((RAND()*LEN(@Chars2BUsed))) + 1
SELECT @CharFound = SUBSTRING(@Chars2BUsed, @LookAt, 1)IF CHARINDEX(@CharFound, @RandomCode)=0
BEGINSELECT @RandomCode = @RandomCode + @CharFound
SELECT @Chars2BUsed = REPLACE(@Chars2BUsed, @CharFound, '')SELECT @iCnt = @iCnt + 1
END
END
View 2 Replies
View Related
Jun 22, 2007
This (demo) statement is fine in Access, and so far as I can see, shouldbe OK in SQL Server.But Enterprise Manager barfs at the final bracket. Can anyone helpplease?select sum(field1) as sum1, sum(field2) as sum2 from(SELECT * from test where id < 3unionSELECT * from test where id 2)In fact, I can reduce it to :-select * from(SELECT * from test)with the same effect - clearly I just need telling :-)cheers,Jim--Jima Yorkshire polymoth
View 4 Replies
View Related
Nov 23, 2004
I am using @strsql to construct the where condition for a select query.
Can you please correct my syntax.
DECLARE @strsql nvarchar(2000)
IF @ProgNO <> '' then
strsql = WHERE ProgNO = @ProgNO
end if
If @ProjNO <> '' then
if strsql <> '' then
strsql = strsql & " and ProjNO =@ProjNO
ELSE
strsql = wHERE ProjNO =@ProjNO
END IF
END IF
Thank you very much.
View 9 Replies
View Related
Nov 24, 2005
This is probably a very simple question but i would appreciate some helpwith the correct syntax for and update stored procedureI have created user form that allows the user to update the name and address fields in a datatable called customers based on the input value customer ID = ( datatable/Customers)customerIDI have got this far and then got lost:Create SP_UpdateCustomer(@customerID, @name, @address)As Update customers ( name, address)Where customerID = @customerID GOCould anyone tell me what the correct sntax should be.many thanksMartin
View 3 Replies
View Related
Feb 17, 2006
I have a interger stored in x.
I want to use x in a SELECT statement like so :
SELECT * from aTable WHERE A_Column = x
This select statement is then assigned to and passed as a string like :
sql = "SELECT * from aTable WHERE A_Column = x"
How does the x get interpreted correctly ?
View 1 Replies
View Related
Sep 21, 2006
Hi,I'm new to ASP.NET, and am currently looking into XML.I'm trying to write XML using data from an SQL Server 2000 table. But I seem to be getting the following error regarding the SQL Server connection:Compiler Error Message: CS1502: The best overloaded method match for 'System.Data.SqlClient.SqlCommand.SqlCommand(string, System.Data.SqlClient.SqlConnection)' has some invalid argumentsSource Error:Line 23: {
Line 24: SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
Line 25: mySqlDataAdapter.SelectCommand = new SqlCommand(queryString, connString);
Line 26: mySqlDataAdapter.Fill(myDataSet);
Line 27: return myDataSet;Source File: c:InetpubwwwrootmappingcreateGeoRSSFile.aspx.cs Line: 25 This is my code:using System;
using System.Data;
using System.Data.SqlClient ;
using System.Configuration;
using System.Collections;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
public partial class createGeoRSSFile : System.Web.UI.Page
{
protected void Page_Load(object sender, DataSet myDataSet, EventArgs e)
{
string connString = "server=SQLSERV1;database=Historical_Statistics;UID=dbuser;PWD=Password";
string queryString = "SELECT Town, PostCode, Latitude, Longitude FROM UKPostCodes";
using (SqlConnection mySqlConnection = new SqlConnection(connString))
{
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = new SqlCommand(queryString, connString);
mySqlDataAdapter.Fill(myDataSet);
return myDataSet;
}
// Create a new XmlTextWriter instance
XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, Encoding.Unicode);
// Start writing!
writer.WriteStartDocument();
writer.WriteStartElement("item");
// Creating the <town> element
writer.WriteStartElement("town");
writer.WriteElementString("PostCode",myDataSet .Tables[1].Columns("PostCode"));
writer.WriteElementString("geo:lat",myDataSet.Tables[1].Columns("Latitude"));
writer.WriteElementString("geo:lon", myDataSet.Tables[1].Columns("Longitude"));
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
writer.Close();
}
}What seems to be causing this error?Thanks.
View 4 Replies
View Related
Mar 12, 2008
Hi all,
I use a "Exec DTS 2000" task.
I have a variable user::MYVAR in my SSIS package, wich value is "PARENT".
I pass this variable as an outer variable to my dts 2000 package, wich receive it correctly, and then update it to "UPDATED".
After this task finishes, when I come back to SSIS, MYVAR is still at "PARENT".
Is it possible to see the update from the parent package ?
Thanks
View 6 Replies
View Related
Mar 11, 2008
I've been looking around but haven't yet found the syntax for usage of global variables in an SQL Task.
I've set the global variable Id (see code below):
if (select field from table where id = @[User::id]) is null
select top 1 1 as response from table
else select top 1 0 as response from table
My objective with it is to set another global variable (@isNull). Supposably, when the selection returns null, I should set the variable to null, I did it by using the selections and mapping the response to that variable (is ther a better way to do so?).
When I try to execute this, it says the variable has not been defined.
Here is the error:
Error: Must declare the variable '@'.
I've also tryed it withou the brackets and the User:: thing in the beggining, (@id directly) and here is the response:
Error: Must declare the variable '@id'.
How should I access the global variables in the SQL code?
(BTW, I've checked the field in execution time and it is set to 23, the correct Id, so the block that preceedes this one is working properly)
Thanks,
View 6 Replies
View Related
Nov 10, 2003
I have the following .bat file that I call to register users to my MSDE instance...
echo osql -E -S %COMPUTERNAME%OfficiumInstance -Q "sp_grantlogin '" + %COMPUTERNAME% + "ASPNET'"
echo osql -E -S %COMPUTERNAME%OfficiumInstance -d Officium -Q "sp_grantdbaccess '" + %COMPUTERNAME% + "ASPNET'"
echo osql -E -S %COMPUTERNAME%OfficiumInstance -d Officium -Q "sp_addrolemember 'db_owner', '" + %COMPUTERNAME% + "ASPNET'"
My question is how do I correctly append %COMPUTERNAME% as a string to
I have tried using + signs...
"sp_grantlogin '" + %COMPUTERNAME% + "ASPNET'"
But that doesn't work.
I have looked for .bat file tutorials on the web but can't find the correct way to do this.
Greg
View 1 Replies
View Related
Sep 30, 2015
I am having trouble finding the correct syntax to access a variable. I have a variable defined in the Variables window: The variable name is formatedDate. The DataType is String.
I am successfully setting the value of the variable in a Execute SQL Task. The SQL is as follows:
SELECT LEFT(CONVERT(VARCHAR, MAX(ReportDate), 120), 10) as formatedDate
from DimReportDates
The Result Set is set to “Single Row” and properly set up.
No problem so far. I can see with a watch that the variable has the correct value, something like:
‘2015-09-30’
Now, in a subsequent step, a Data Flow Task, I want to access the variable. Actualy it is in the SQL statement of a OLE DB source in the Data Flow… I have the following:
Declare @sDate smalldatetime
SELECT @sDate = xxxxx
I have tried several things substituting xxxxx above, but nothing seems to work. One variation was
@[User::formatedDate])
Another was
((DT_WSTR, 10) @[User::formatedDate]).
I think I’m close, but just can’t get it. What is the correct syntax.
View 4 Replies
View Related
Apr 11, 2006
I have some VB.NET code that starts a transaction and after that executes one by one a lot of queries. Somehow, when I take out the transaction part, my queries are getting executed in around 10 min. With the transaction in place it takes me more than 30 min on one query and then I get timeout.
I have checked sp_lock myprocessid and I've noticed there are a lot of exclusive locks on different objects. Using sp_who I could not see any deadlocks.
I even tried to set the isolation level to Read UNCOMMITED and still have the same problem.
As I said, once I execute my queries without being in a transaction everything works great.
Can you help me to find out the problem?
Thanks,
Laura
View 11 Replies
View Related
Feb 23, 2007
I am currently having a problem where my SQL server seems to lock any variables to 1000 characters (ie. varchar(8000) can only hold 1000)I have read in numerous sources it was possible to change that limit so the varchar can truly hold the 8000 characters and not stop at 1000, but there was no info on how to do this.I am looking for a "How to" to put this limit to 8000.Thank you!
View 10 Replies
View Related
Oct 26, 2006
Hi
I am developing custom dataflow component ,I need to get the of variables of the current package in the component , how can i get it?
Thanks
Mani
View 6 Replies
View Related
Jan 13, 2006
Hello,I've been searching the web for quite some time to resolve the problemof "1/1/1900" returning in a datetime field in SQL that resulted from ablank (not NULL) value being passed to it through an ASP page.The solution is that a NULL value needs to passed to SQL from ASP.Thats fine...I understand the why the problem is happening and thesolution around it. HOWEVER, I can't seem to get the proper syntax towork in the ASP page. It seems no matter what I try the "1/1/1900"still results. Below are a few variations of the code that I havetried, with the key part being the first section. Does anyone have anysuggestions?!?!?______________cDateClosed = ""If(Request.Form("dateClosed")= "") ThencDateClosed = (NULL)end ifsql="UPDATE rfa SET "&_"dateClosed='"& cDateClosed &"', "&_"where rfaId='"& Request.Form("RFAID")&"'"_____________________________cDateClosed = ""If(Request.Form("dateClosed") <> "") ThencDateClosed = (NULL)end ifsql="UPDATE rfa SET "&_"dateClosed='"& cDateClosed &"', "&_"where rfaId='"& Request.Form("RFAID")&"'"_____________________________cDateClosed = ""If(Request.Form("dateClosed")= "") ThencDateClosed = NULLend ifsql="UPDATE rfa SET "&_"dateClosed='"& cDateClosed &"', "&_"where rfaId='"& Request.Form("RFAID")&"'"_______________Thanks in advance!!!!
View 7 Replies
View Related
Feb 21, 2008
Hello,
I was wondering if anyone can explain the positives and negatives of using a single stored procedure that contains one or more distinct queries. I know there are problems with dynamic SQL but I am not proficient enough to know whether this falls under that umbrella.
For clarification, what I am referring to is this: In a single stored procedure, I have a parameter called Query_ID that is used to identify which query in the sproc that I want to execute. Then from my ASP page, I simply pass the appropriate value for Query_ID. So:
IF @QUERY_ID = 1
BEGIN
SELECT [whatever]
FROM [tbl1]
WHERE [conditions]
GROUP BY [something]
ORDER BY [somethingelse]
END
ELSE
IF @QUERY_ID = 2
BEGIN
SELECT [whatever]
FROM [tbl2]
WHERE [conditions]
GROUP BY [something]
ORDER BY [somethingelse]
END
END
I hope that makes sense. Thanks in advance.
View 7 Replies
View Related
Feb 20, 2015
I'm looking for the correct syntax to pull back duplicate vendors based on 6 fields from two different tables. I want to actually see the duplicate vendor information (not just a count). I am able to pull this for one of the tables, something like below:
select *
from VendTable1 a
join ( select firstname, lastname
from VendTable1
group by firstname, lastname
having count(*) > 1 ) b
on a.firstname = b.firstname
and a.lastname = b.lastname
I'm running into issues when trying to add the other table with the 4 other fields.
View 5 Replies
View Related
Jan 27, 2005
Hi,
I'm writing an Access pass-through query against a SQL server backend and I need some advice on passing parameters. Currently I use vba to substitute the literal values for the parameters prior to passing the query to SQL Server. However, I am going through a loop thousands of times with different literals for these parameters which causes the server's cache to fill up. In Oracle, there is a way to use bind variables for the parameters so that only one copy of the query is cached.
Does anyone know how I can do this in SQL Server?
For instance, I have 20,000 employees and I'm pulling info by SS#:
Select * from EmpTable where SS_number = [SSN]
Is there a way I can pass this query to SQL Server and then pass the value of [SSN] as I loop through the dataset?
Thanks.
View 5 Replies
View Related
Nov 30, 2007
I'm trying to understand how to use SSIS variables within SQL commands and which Data Flow toolbox objects I can use for this. My simple package has a OLE DB Source object that returns the rows in a table. For the next operation, the output from the OLE DB Source is input into a Lookup data flow transformation where there is a select query that returns another value from a different table...
select bla from myTable where dbname = db_name()
The output is then passed on to an OLE DB Destination.
The above lookup query only works because, it so happens, that I could get a unique and correct result back filtered by current database name. However, due to other required changes, I now have introduce more 'where clauses'. I have all the necessary clause information in SSIS variables (iterated via a For Each loop). I would like do something like...
select bla from myTable where dbname = ? and bla_type = ?
However, there isn't a facility for Parameters in the Lookup object's 'use results of a SQL query'. I can see that I can use parameters in the OLE DB Source object by changing the 'data access mode' to SQL Query. However, it doesn't seem valid to join two OLE DB Source objects together in the data flow? I can't see any other suitable objects in the Data Flow toolbox. Ideally, I would be able to use Parameters in the Lookup object or some other object that would do the same job.
Thanks,
Clive
View 6 Replies
View Related
Feb 10, 2008
Hi
Is it possible To pass an SQL command to a ASp.net web service as system.data.SQLclient.sqlcommand?
That means is ispossible to pass the actuall sql command instead of just the string?
If yes how can you do that??
Cheers
View 1 Replies
View Related
May 23, 2007
I have an openquery statement with a parameter embeded as a variable:
declare @product varchar(3)
set @product= 'ABC'
select * from openquery(SomeServer,'
SELECT Description, Size
FROM Products
WHERE
Group = ''XY'' AND
Code = ''' + @product + '''')
When I run it I get the following message:
Msg 102, Level 15, State 1, Line 8
Incorrect syntax near '+'.
When I hard code the "Code" value, like so:
Code = ''ABC''')
...it works fine.
I am at a loss and would appreciate any help on this.
Thanks in advance
SQL Servant
View 7 Replies
View Related