Exception Error - Incorrect Syntax Near '('. Inline UPDATE Command

May 4, 2007

Hi,

Here's the code I've used to try and update a new user's IP Address to a Table called Customer who's key field in the UserId:

Getting the Exception Error   "Incorrect Syntax near'('. "                 Any ideas?

protected void ContinueButton_Click(object sender, EventArgs e)

{

//Get the ip address and put it into the customer table - (the instance of this user now exists)

 

MembershipUser _membershipUser = Membership.GetUser(); //This gets the active user if there is someone logged in...

Guid UserId = (Guid)_membershipUser.ProviderUserKey; //This gets the userId for the currently logged in user

string IPAddress = Request.UserHostAddress.ToString();//This gets the IPAddress of the currently logged in user

string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

using (System.Data.SqlClient.SqlConnection con =new System.Data.SqlClient.SqlConnection(cs))

{

con.Open();

System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();

cmd.Connection = con;

cmd.CommandType = System.Data.CommandType.Text;

 

cmd.CommandText = "UPDATE Customer SET(IP_Address = @IP_Address) WHERE (UserId = @UserId)";

cmd.Parameters.Add("@UserId", System.Data.SqlDbType.UniqueIdentifier).Value = UserId;

cmd.Parameters.Add("@IP_Address", System.Data.SqlDbType.Char, 15).Value = IPAddress;

cmd.ExecuteNonQuery();

 

con.Close();

}

 Thanks.

View 5 Replies


ADVERTISEMENT

Incorrect Syntax Near [SQL UPDATE COMMAND] &> Cmd.ExecuteNonQuery()

Nov 7, 2007

Please let me know what is wrong with my code below. I keep getting the "Incorrect syntax near 'UpdateInfoByAccountAndFullName'." error when I execute cmd.executenonquery.  I highlighted the part that errors out.  Thanks a lot.  ---------------------------------------------------------------------------------------------------------------------------         public bool Update(                string newaccount, string newfullname, string rep, string zip,                string comment, string oldaccount, string oldfullname            )        {            SqlConnection cn = new SqlConnection(_connectionstring);            SqlCommand cmd = new SqlCommand("UpdateInfoByAccountAndFullName", cn);            cmd.Parameters.AddWithValue("@newaccount", newaccount);            cmd.Parameters.AddWithValue("@newfullname", newfullname);            cmd.Parameters.AddWithValue("@rep", rep);            cmd.Parameters.AddWithValue("@zip", zip);            cmd.Parameters.AddWithValue("@comments", comment);            cmd.Parameters.AddWithValue("@oldaccount", oldaccount);            cmd.Parameters.AddWithValue("@oldfullname", oldfullname);            using (cn)            {                cn.Open();                return cmd.ExecuteNonQuery() > 1;            }        }

View 12 Replies View Related

Error Incorrect Syntax Near '('. When Doing Update() From Code, VB

Apr 22, 2007

Hi all
My error is as follows: Incorrect syntax near '('.Line 27:         acceptOrDeclineFriendship.UpdateParameters.Add("Response", answer)Line 28:         acceptOrDeclineFriendship.UpdateParameters.Add("FriendID", friend_id)Line 29:         acceptOrDeclineFriendship.Update()Line 30: Line 31:     End Sub
Bear with me... I have a page where i use a repeater control to list users who have requested to be friends with the currently online user. The 'getFriendRequests' query looks like this:
SelectCommand="SELECT * FROM Friends, UserDetails WHERE (Friends.UserID = UserDetails.UserID) AND (FriendID = @UserID) AND (ApprovedByFriend = 'False') ORDER BY Friends.Requested DESC">This works. 
Within each repeater template, there are 2 buttons, 'Accept' or 'Decline', like this: <asp:Repeater ID="Repeater1" runat="server" DataSourceID="getFriendRequests">
<ItemTemplate>
(other stuff like avatar and username etc)
<asp:Button ID="accept" runat="server" Text="Accept" commandName="Accept" commandArgument='<%#Eval("UserID")%>' onCommand="Accept_Decline_Friends"/>
<asp:Button ID="decline" runat="server" Text="Decline" commandName="Decline" commandArgument='<%#Eval("UserID")%>' onCommand="Accept_Decline_Friends"/>
</ItemTemplate>
</asp:Repeater>
The code-behind (VB) which deals with this is as follows: Protected Sub Accept_Decline_Friends(ByVal sender As Object, ByVal e As CommandEventArgs)

'retrieve id of requestee and the answer accept/decline
Dim friend_id As String = e.CommandArgument.ToString
Dim answer As String = e.CommandName.ToString

'add the parameters
acceptOrDeclineFriendship.UpdateParameters.Add("Response", answer)
acceptOrDeclineFriendship.UpdateParameters.Add("FriendID", friend_id)
acceptOrDeclineFriendship.Update()

End Sub
Since the buttons are being created dynamically, this is how i track 1. the response from the currently logged in user 'Accept/Decline' and 2. who they are responding to (by their uniqueid)
This relates to a sqlDataSource on my .aspx page like this: <!---- update query when user has accepted the friendship ---->
<asp:SqlDataSource ID="acceptOrDeclineFriendship" runat="server" ConnectionString="<%$ xxx %>"
UpdateCommand="UPDATE Friends SET (ApprovedByFriend = @Response) WHERE (FriendID = @UserID) AND (UserID = @FriendID)">
<UpdateParameters>
<asp:ControlParameter Name="UserID" ControlID="userIdValue" />
</UpdateParameters>
</asp:SqlDataSource>
 Which is meant to update my 'Friends' table to show that 'ApprovedByFriend' (the logged in user) is either 'Accept' or 'Decline', and record who's request was responded to.
I hope this is clear, just trying to suppy all of the information! The error appears to be saying that I have an issue with my code-behind, where i am telling the sqlDataSource above to UPDATE. What I can say is that for each button in the repeater, the 2 variables 'friend_id' and 'answer' are picking up the correct values.
Can anyone see any obvious problems here? Any help is very much appreciated as i am well and truley stuck!

View 1 Replies View Related

Incorrect Syntax Exception When Prefacing SP Names With Dbo. And Named Parameter Issues

Aug 17, 2006

We're currently trying to evaluate SQLJDBC 2005 1.1 June CTP's support for database mirroring automatic failover. Unfortunately we're getting unexpected exceptions for calls that work fine w/ jtds that our blocking our ability to perform these evaluations without us making substantial changes to our codebase.

The first issue is with the name used when calling a stored procedure -- SP names that start with "dbo." give us the following error:

com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near '.'. src:{call dbo.xyz(?,?,?,?,?,?,?,?)}

The call will work if we change the SQL statement to {call xyz(...)}. I don't understand why we would need to do this, especially given that the documentation for the driver shows call statements with the "dbo." prefix.

We're also having problems using named parameters with stored procedures (for both in and out parametes). Our code has parameter names of the form "@param" as is standard with TSQL (and is required when using jtds). However, this won't work with SQLJDBC -- it only seems to accept parameter names w/o the leading "@". Why is this so?

Finally, we were able to cause a NullPointerException within the driver due to an incorrectly built Properties object that contained an Integer for loginTimeout instead of a String:
java.lang.NullPointerException
at java.util.Hashtable.put(Hashtable.java:396)
at java.util.Properties.setProperty(Properties.java:128)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.fixupProperties(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.mergeURLAndSuppliedProperties(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(Unknown Source)
While this was due to a bug in our code I would think that such common errors would be better handled.

View 6 Replies View Related

Update Command Exception

Apr 15, 2008

HI
i make form to update some data in table
the code:protected void Update_Click(object sender, EventArgs e)
{SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=AinShams;Integrated Security=True");
con.Open();SqlCommand cmd = con.CreateCommand();
int iid = int.Parse(DropDownList1.SelectedValue);string name2 = DropDownList1.SelectedItem.Text;
string des2 = txt_dsc.Text;string loc2 = txt_loc.Text;
int act=-1;if (active_check.Checked == true)
{
act = 1;
}
else
{
act = 0;
}int yearsc = int.Parse(txt_yc.Text);
int pr = -1;if (prep_ck.Checked == true)
{
pr = 1;
}
else
{
pr = 0;
}
cmd.CommandText = "update Faculties set FacultyName=" +name2+ ",FacultyDescription=" + des2 + ",FacultyLocation=" + loc2 + ",FacultyActive='" + act + "',FacultyYearsCount='" + yearsc + "',FacultyIsPrep='" + pr + "' where FacultyId='" + iid + "'";
//cmd.CommandText = "update Faculties set FacultyName=@name,FacultyDescription=@des,FacultyLocation=@loc,FacultyActive=@act,FacultyYearsCount=@years,FacultyIsPrep=@p where FacultyId=@iid";
// cmd.CommandText = "update Faculties set FacultyDescription=" + des2 + " where FacultyId='" + iid + "'";
//cmd.Parameters.AddWithValue(@name, name);
//cmd.Parameters.AddWithValue(@des, des);
//cmd.Parameters.AddWithValue(@loc, loc );
//cmd.Parameters.AddWithValue(@act, act);
//cmd.Parameters.AddWithValue(@years, yearsc);
//cmd.Parameters.AddWithValue(@p , pr);
//cmd.Parameters.AddWithValue(@iid, iid );
cmd.ExecuteNonQuery();
con.Close();
 }
 
but it give mw exception:
Server Error in '/try' Application.


Invalid column name 'sara'.Invalid column name 'mayada'.Invalid column name 'mmmmmm'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'sara'.Invalid column name 'mayada'.Invalid column name 'mmmmmm'.Source Error:



The source code that generated this unhandled exception can only be shown when compiled in debug mode. To enable this, please follow one of the below steps, then request the URL:1. Add a "Debug=true" directive at the top of the file that generated the error. Example:  <%@ Page Language="C#" Debug="true" %>or:2) Add the following section to the configuration file of your application:<configuration>   <system.web>       <compilation debug="true"/>   </system.web></configuration>Note that this second technique will cause all files within a given application to be compiled in debug mode. The first technique will cause only that particular file to be compiled in debug mode.Important: Running applications in debug mode does incur a memory/performance overhead. You should make sure that an application has debugging disabled before deploying into production scenario. Stack Trace:



[SqlException (0x80131904): Invalid column name 'sara'.
Invalid column name 'mayada'.
Invalid column name 'mmmmmm'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +180
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +68
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +199
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2411
System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async) +196
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) +380
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +115
Manage_Faculties22.Update_Click(Object sender, EventArgs e) +879
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +75
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +97
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4886



Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433
 
when i click the update button this error appear
sara mayada mmmmm the data i enter in the form
what couse this error please?
Thanx in advance

View 1 Replies View Related

Update Command Syntax ...

Feb 3, 2008

Hi here's a bit of code. What am I doing wrong here?  Visual Studio isn't even accepting the Set word on line 56. It deletes it everytime.  What am I doing wrong here? Why is Visual studio putting the parenthese around the table name in 55? I generated an update query for my Websitetableadapter. Here it is:
UPDATE [tblWebSite] SET [Rating] = @Rating, WHERE (([WebSiteID] = @Original_WebSiteID))
How do I use this to update the Rating column after I've done my calculation below?

1    Imports RatingsTableAdapters2    3    4    Partial Class admin_ratings5        Inherits System.Web.UI.Page6    7        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load8            Dim I As Integer = 09            Dim J As Integer = 010           Dim Rating As Integer11           Dim Rate As Decimal12           Dim tblwebsiteAdapter As New tblWebSiteTableAdapter13           Dim tblWebsite As ratings.tblWebSiteDataTable14           tblWebsite = tblwebsiteAdapter.GetData()15           For Each tblwebsiteRow As ratings.tblWebSiteRow In tblWebsite16               Rate = 017               Dim tblLinkAdapter As New tblLinkTableAdapter18               Dim tblLink As ratings.tblLinkDataTable19               Dim tblLinkTot As ratings.tblLinkDataTable20               tblLink = tblLinkAdapter.GetSuccessfulExchanges(tblwebsiteRow.WebSiteID)21               tblLinkTot = tblLinkAdapter.GetTotalLinks(tblwebsiteRow.WebSiteID)22               For Each tbllinkRow As ratings.tblLinkRow In tblLink23                   If tbllinkRow.LinkID < 1 Then24                       I = 0.125                   Else : I = I + 126                   End If27               Next28               If I <> 0 Then29                   For Each tbllinktotrow As ratings.tblLinkRow In tblLinkTot30                       If tbllinktotrow.LinkID < 1 Then31                           J = 0.132                       Else : J = J + 133                       End If34                   Next35               End If36               If I <> 0 And J <> 0 Then37   38                   Rate = I / J39                   If Rate <= 0.3 Then40                       Rate = 041                   End If42                   If Rate <= 0.5 Then43                       Rate = 144                   End If45                   If Rate <= 0.65 Then46                       Rate = 247                   End If48                   If Rate <= 0.75 Then49                       Rate = 350                   End If51               End If52   53               Response.Write(tblwebsiteRow.WebSiteID & " " & tblwebsiteRow.SiteURL & " Rating: " & Rate & "54               I = 055               J = 056               Update(tblWebsite)57               Rating = Rate58               where(tblwebsiteRow.WebSiteID <> 0)59           Next60       End Sub61   End Class 

View 34 Replies View Related

Incorrect Syntax Error

Sep 17, 2007

I am getting an error saying, "Incorrect syntax near keyword 'ON'" Could someone please help? Here is my code: 
str = "SELECT FAC_REQUEST.*, StateFAC.*, STATUS.sStatus, FAC_TYPE.Facility_Type FROM FAC_TYPE INNER JOIN ((FAC_REQUEST INNER JOIN STATUS ON FAC_REQUEST.iStatusID = STATUS.iStatusID) ON StateFAC.DVN = FAC_REQUEST.DVN) ON FAC_TYPE.Faciltiy_Type = FAC.FacilityType WHERE iRequestID=" & iRequestID
Thanks

View 6 Replies View Related

Error Incorrect Syntax Near ')'

Mar 7, 2008

Hi,
   When i exceute my report i get the following .. An error occured during local report processing. Query exceuteion failed for dataset 'orders' Incorrect syntax near ')'
If i give NULL i get the above error... But if give one or 2 values it works. but If I run the query in my Sql server mgt studio it works fine too and i run in the BIDS or VS2005 it works fine.. but something happens when i generate the reports... ALTER Procedure [dbo].[usp_GetOrdersByOrderDate]
@ClientId nvarchar(max)= NULL,
@StartDate datetime,
@EndDate datetime
AS
Declare @SQLTEXT nvarchar(max)
If @ClientId IS NULL
Begin
Select
o.OrderId,
o.OrderDate,
o.CreatedByUserId,
c.LoginId,
o.Quantity,
o.RequiredDeliveryDate,
cp.PlanId,
cp.ClientPlanId
FROM
[Order] o
Inner Join ClientPlan cp on o.PlanId = cp.PlanId
Inner Join ClientUser c on o.CreatedByUserId = c.UserId
WHERE
--cp.ClientId = @ClientId
--AND
o.OrderDate BETWEEN @StartDate AND @EndDate
ORDER BY
o.OrderId DESC
END
ELSE
BEGIN
SELECT @SQLTEXT = 'Select
o.OrderId,
o.OrderDate,
o.CreatedByUserId,
c.LoginId,
o.Quantity,
o.RequiredDeliveryDate,
cp.PlanId,
cp.ClientPlanId
FROM
[Order] o
Inner Join ClientPlan cp on o.PlanId = cp.PlanId
Inner Join ClientUser c on o.CreatedByUserId = c.UserId
WHERE
cp.ClientId in (' + @ClientId + ')
AND
o.OrderDate BETWEEN ' + Convert(varchar,@StartDate) + ' AND ' + convert(varchar, @EndDate) + '
ORDER BY
o.OrderId DESC'
execute (@SQLTEXT)

END
any help will be appreciated.

Regards

Karen
 

View 13 Replies View Related

Incorrect Syntax - Error Help

Jan 14, 2005

Hi! I need some help with this error which I'm unable to understand.

Any help will be highly appreciated.

<Error>
Line 1: Incorrect syntax near 'Number'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near 'Number'.

Source Error:

Line 69: Dim da As SqlDataAdapter = New SqlDataAdapter(cmd)
Line 70: Dim ds As DataSet = New DataSet
Line 71: da.Fill(ds, "Equip")
Line 72:
Line 73: dgdSearch.DataSource = ds.Tables("Equip").DefaultView

Source File: c:inetpubwwwrootEquip logDemoWebForm3.aspx.vb Line: 71

Stack Trace:

[SqlException: Line 1: Incorrect syntax near 'Number'.]
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream)
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
System.Data.SqlClient.SqlCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
System.Data.Common.DbDataAdapter.FillFromCommand(Object data, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, String srcTable)
Demo.WebForm3.butSearch_Click(Object sender, EventArgs e) in c:inetpubwwwrootEquip logDemoWebForm3.aspx.vb:71
System.Web.UI.WebControls.Button.OnClick(EventArgs e)
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
System.Web.UI.Page.ProcessRequestMain() +1292

</Error>


Private Sub butSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles butSearch.Click
Dim objConnection As SqlConnection
Dim objCommand As SqlCommand
Dim objAdapter As SqlDataAdapter
Dim objDataReader As SqlDataReader
Dim objDataSet As DataSet
Dim strSearch As String
Dim StrSQLQuery As String
'Dim mySQL As String

'Get Search
strSearch = txtSearch.Text

'If there's nothing to search for then don't search
' o/w build our SQL Query execute it.
If Len(Trim(strSearch)) > 0 Then
'Set up our connection.
Dim strConn As String = ("server=(local);Integrated Security=SSPI;database=Equipment Log")

'-- setup the select command
Dim mySQL As String = "Select * From Equip Where " & ddlSearch.SelectedValue.ToString() & " Like '" & txtSearch.Text & " %' Order by DemoNum"

Dim MyConn As New SqlConnection(strConn)
'--create the SqlCommand object (a connection would need to be set up too)
Dim cmd As SqlCommand = New SqlCommand(mySQL, MyConn)
MyConn.Open()
'--execute the query and fill a dataset with the results
Dim da As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim ds As DataSet = New DataSet
da.Fill(ds, "Equip")

dgdSearch.DataSource = ds.Tables("Equip").DefaultView

'Create new command object passing it our SQL Query
'and telling it which connection to use.
objCommand = New SqlCommand(strSearch, objConnection)

'DataBind DG to DS
ddlSearch.DataBind()
dgdSearch.DataBind()
MyConn.Close()

Else
txtSearch.Text = "Enter Serach Here"
End If

View 1 Replies View Related

Incorrect Syntax Error?

Jan 2, 2006

I am getting the following error when attempting to call a certain function:
"Incorrect Syntax near spListPrograms, Line 1"
Here is the sproc:
ALTER PROCEDURE spListPrograms
@parentID int = 0
AS
SELECT pwbsID, pwbsTitle FROM ProgramWBS WHERE pwbsParent = @parentID
It is being called from this function:
    Public Shared Function ListProgramChildNodes(Optional ByVal parentID As Integer = 0) As SqlDataReader
        Dim cmd As New SqlCommand("spListPrograms", strConn)
        cmd.Parameters.AddWithValue("@parentID", parentID)
        Try
            strConn.Open()
            Return cmd.ExecuteReader(CommandBehavior.CloseConnection)
 
        Catch e As SqlException
            Dim errorMessages As String = ""
            Dim i As Integer
 
            For i = 0 To e.Errors.Count - 1
                errorMessages += "Index #" & i.ToString() & ControlChars.NewLine _
                               & "Message: " & e.Errors(i).Message & ControlChars.NewLine _
                               & "LineNumber: " & e.Errors(i).LineNumber & ControlChars.NewLine _
                               & "Source: " & e.Errors(i).Source & ControlChars.NewLine _
                               & "Procedure: " & e.Errors(i).Procedure & ControlChars.NewLine
            Next i
 
            MsgBox(errorMessages)
        Finally
            strConn.Close()
        End Try
    End Function
 
The sproc works just fine when I execute it from the database directly in SQl Express. What could cause an incorrect syntax error? There's hardly any syntax there for an error to occur  Thanks for any help you can give me.

View 2 Replies View Related

Incorrect Syntax Error

Mar 8, 2004

hi. i am relatively new to sql. i am wondering how to resolve my "incorrect syntax error" on an IP Address string i am trying to add.
the table has IPAddress as data type "text" and length 16 (which won't let me change the length). It seems that sql is looking for a data type with no more than one decimal (money, float, etc). How do i resolve this? thanks in advance. Peter

View 7 Replies View Related

Incorrect Syntax Near The Keyword 'from'. Line 1: Incorrect Syntax Near ')'.

May 27, 2008

This is the error it gives me for my code and then it calls out line 102.  Line 102 is my  buildDD(sql, ddlPernames)  When I comment out this line the error goes away, but what I don't get is this is the same way I build all of my dropdown boxes and they all work but this one.  Could it not like something in my sql select statement.  thanksPrivate Sub DDLUIC_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DDLUIC.SelectedIndexChanged
Dim taskforceID As Byte = ddlTaskForce.SelectedValueDim uic As String = DDLUIC.SelectedValue
sql = "select sidstrNAME_IND from CMS.dbo.tblSIDPERS where sidstrSSN_SM in (Select Case u.strSSN from tblAssignedPersonnel as u " _
& "where u.bitPresent = 1 and u.intUICID in (select intUICID from tblUIC where intTaskForceID = " & taskforceID & " and strUIC = '" & uic & "'))"ddlPerNames.Items.Add(New ListItem("", "0"))
buildDD(sql, ddlPerNames)
 
End Sub

View 2 Replies View Related

Error 156: Incorrect Syntax Near The Keyword WHEN.

Jan 16, 2008

Hi i have the following code in my sql database;CASE dbo.tblWorkSchedule.WorkScheduleType_ID WHEN 1 THENCASE IsNull(dbo.tblSurvey.WorkScheduleOverallStatus_ID,0) WHEN 4 THENdbo.tblWorkSchedule.UpliftedRate ELSE dbo.GetSWT_PropertyYearPeriodRate (IsNull(tblRateSchedule.WorkType_ID,0)  ,tblWorkSchedule.WorkSchedule_ID  , tblSurvey.PropertyYear_ID , tblSurvey.PropertyPeriod_ID )  END   I want to add the following lines to it, however it gives me an error "Error 156: Incorrect syntax near the keyword "WHEN". What do i need to do, thank you.  WHEN 3 THEN dbo.tblWorkSchedule.UpliftedRate ELSE dbo.GetSWT_PropertyYearPeriodRate (IsNull(tblRateSchedule.WorkType_ID,0)  ,tblWorkSchedule.WorkSchedule_ID  , tblSurvey.PropertyYear_ID , tblSurvey.PropertyPeriod_ID )  END
 
 

View 7 Replies View Related

Error: Incorrect Syntax Near The Keyword 'WHERE'

Feb 28, 2008

Hi,
I am building a website and database system for a university project, and am getting an error message when inserting data to a table (error message = "System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'WHERE'.").  I would be most grateful if anybody could point out where I am going wrong!  My code is;
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class Default2 : System.Web.UI.Page
{protected void Page_Load(object sender, EventArgs e)
{if ((Session["sUserName"]) == null)
{Response.Redirect("Default.aspx");
}
else
{Convert.ToString(Session["sUserName"]);
}
}protected void Register(object sender, EventArgs e)
{
//Create the ConnectionSqlConnection sqlConn =
new SqlConnection("server=Acer-Laptop\SQLEXPRESS; database=NeuCar; Trusted_Connection=true");
//Open the connection
sqlConn.Open();
//Create the Command, passing in the SQL statement and the ConnectionString queryString = "INSERT INTO Member (FirstName, LastName, Title, Email, AddressLine1, AddressLine2, TownOrCity, County, Postcode) VALUES(@myFirstName, @myLastName, @myTitle, @myEmail, @myAddressLine1, @myAddressLine2, @myTownOrCity, @myCounty, @myPostcode) WHERE Member (UserName = @myUserName); ";
SqlCommand cmd = new SqlCommand(queryString, sqlConn);cmd.Parameters.Add(new SqlParameter("@myUserName", Session["sUserName"]));
cmd.Parameters.Add(new SqlParameter("@myFirstName", FirstNameTextBox.Text));cmd.Parameters.Add(new SqlParameter("@myLastName", LastNameTextBox.Text));
cmd.Parameters.Add(new SqlParameter("@myTitle", TitleTextBox.Text));cmd.Parameters.Add(new SqlParameter("@myEmail", ConfirmEmailTextBox.Text));
cmd.Parameters.Add(new SqlParameter("@myAddressLine1", AddressLine1TextBox.Text));cmd.Parameters.Add(new SqlParameter("@myAddressLine2", AddressLine2TextBox.Text));
cmd.Parameters.Add(new SqlParameter("@myTownOrCity", TownOrCityTextBox.Text));cmd.Parameters.Add(new SqlParameter("@myCounty", CountyTextBox.Text));cmd.Parameters.Add(new SqlParameter("@myPostcode", PostcodeTextBox.Text));
cmd.ExecuteNonQuery();
Response.Redirect("Register.aspx");
//Close the connection
sqlConn.Close();
}
}
Also, is this line of code correct for passing a session variable into a parameter?;
cmd.Parameters.Add(new SqlParameter("@myUserName", Session["sUserName"]));
Many thanks for your time and help!
Chima

View 5 Replies View Related

Error-Line 1: Incorrect Syntax Near '='

Aug 21, 2004

hi,

i got this error when i run app.

---------------
Line 1: Incorrect syntax near '='.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near '='.

Source Error:


Line 40: Dim adpt As New SqlDataAdapter("SELECT * FROM SMS_student_class_master WHERE" & _
Line 41: "stud_id=" & sid, con)
Line 42: adpt.Fill(ds, "SMS_student_class_master")
Line 43: txt.Text = ds.Tables.Item("roll_no").ToString
Line 44: con.Close()


Source File: c:inetpubwwwrootaspnetsmsassignment_d.aspx.vb Line: 42
--------

what should i do?
anyone have any idea?
plz give solution.
it's urgent.

thanks in advance

View 2 Replies View Related

Incorrect Syntax Near &#39;s&#39; Error Message

May 10, 2000

I am moving along but I still get this pesky error. In a field on the user form for comments - when there is a ' character - I get this syntax error. But, I have removed the ' character with this code:
fieldname= Replace(Request.Form("fieldname"), "'", " ")

So how do I get rid of this error? Beats me.
Anyone know of resources I can read about this?

Thanks in advance...................


Set objConn = Server.CreateObject("ADODB.Connection")
Set rs = server.createobject("ADODB.Recordset")

objConn.open "Driver={SQL Server};Server=server;DSN=SQL3;Database=requests;U ID=probe;PWD=;"

strDocument= request.form("qryName")
strName= request.form("name")
strDescription= request.form("description")
strEmail= request.form("email")
StrTeam= request.form("shift")
StrSection= request.form("pickone")
StrComments= request.form("comments")
StrDatein= request.form("datein")
StrType= request.form("type")
StrDcfnumber=CounterHits



sql = "Insert into dcf_submit (qryName,name,description,email_requestor,shift,se ction_pickone,change_type,comments,date_submit,dcf _number) values('" & _
strDocument & "','" & _
strName & "','" & _
strDescription & "','" & _
strEmail & "','" & _
StrTeam & "','" & _
StrSection & "','" & _
StrType & "','" & _
StrComments & "','" & _
StrDatein & "','" & _
StrDcfnumber & "')"

objConn.execute sql

rs.Close
Set rs = Nothing

View 1 Replies View Related

Error - Incorrect Syntax Near Rename

Mar 14, 2012

----change In the name of Table 5 Table 6

Use test
GO
ALTER TABLE NAME tablo5 RENAME TO tablo6;
GO

but error messages::

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'tablo5'.
------------------
------------------
----tablo4 d1 ==> d11 change.
Use test
GO
ALTER TABLE tablo4 RENAME COLUMN d1 TO d11;
GO

error messages::

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'RENAME'

View 1 Replies View Related

Error - Incorrect Syntax Near The Keyword (else)

Nov 12, 2014

I am getting error "Incorrect syntax near the keyword 'else'"

below is my code

declare @a varchar(15), @b Float(12) ,@c Float(12),@m varchar(15),@n Float(15),@av Float(15),@xav float(15)
SELECT @a=reverse(Substring(reverse(remarks),Charindex('tS',REVERSE(remarks))+2,4))
FROM [IVRS_MIS].[dbo].[logs] where app_name='IVFRT_POC' and remarks like '%answered%'
if @a = 1020
SELECT @m = '1022', @n = Count(@a), @av = Count(@a)/4.0 ,@b = substring(MAX(right(node_info, charindex('X',reverse(node_info))-8)),1,5) ,@c=substring(MIN(right(node_info, charindex('X',reverse(node_info))-8)),1,5),@xav=(@b+@c)/2.0
FROM [IVRS_MIS].[dbo].[logs]

[code].....

View 2 Replies View Related

Strange Incorrect Syntax Error

Jul 12, 2007

Hey guys, I'm getting this really strange incorrect sytax error with a program I'm writing in VB.NET for an ASP.NET website.



Here is my code:



Dim mySelectQuery2 As String = "SELECT MAX(TicketID) FROM tblTicket"

Dim myInsertQuery As String = "INSERT INTO tblCaller (TicketID)"

Dim myConnection As New Data.SqlClient.SqlConnection(myConnString)

Dim myCommand As New Data.SqlClient.SqlCommand(mySelectQuery2, myConnection)

Dim myCommand2 As New Data.SqlClient.SqlCommand(myInsertQuery, myConnection)

Dim retvalue As Integer

myConnection.Open()

retvalue = myCommand2.ExecuteNonQuery()

Console.WriteLine(retvalue)

Dim myReader2 As Data.SqlClient.SqlDataReader

myReader2 = myCommand.ExecuteReader()

myReader2.Close()

myConnection.Close()



Now, the actual error I'm getting is "Incorrect syntax near ')'." that is refering to the link of code "retvalue = myCommand2.ExecuteNonQuery()". I've played around with the code a little bit but I just can't seem to make that error go away.



My only guess is that in the "myInsertQuery" I should have "VALUE (...", but I'm not sure what to put there.



If anyone could make any suggestions on what I might want to try, or if you think that you need more information please let me know.



Thanks,

aqzman

View 5 Replies View Related

XML Query Error Incorrect Syntax Near '&&<'

Feb 6, 2007

Hi all,

I use

="<Query><XmlData>" & Parameters!XMLData.Value & "</XmlData><ElementPath>Product {@}</ElementPath></Query>"



and I enter XMLData with value "<Products><Product>Chair</Product><Product>Table</Product></Products>"

for the query expression of the dataset, and I always got error:

Query failed for dataset "Dataset1"

Incorrect syntax near '<'



What's wrong with it?



Thanks,

Jone

View 1 Replies View Related

Error Message Incorrect Syntax Near ')'

Mar 10, 2008



Hi,

When i exceute my report i get the following .. An error occured during local report processing. Query exceuteion failed for dataset 'orders' Incorrect syntax near ')'

If i give NULL i get the above error... But if give one or 2 values it works. but If I run the query in my Sql server mgt studio it works fine too and i run in the BIDS or VS2005 it works fine.. but something happens when i generate the report in preview mode. I am using multivalue parameter
This is my sproc



Code Snippet
ALTER Procedure [dbo].[usp_GetOrdersByOrderDate]

@StartDate datetime,
@EndDate datetime,
@ClientId nvarchar(max)= NULL
AS
Declare @SQLTEXT nvarchar(max)
if @ClientId is NULL
BEGIN
SELECT
o.OrderId,
o.OrderDate,
o.CreatedByUserId,
c.LoginId,
o.Quantity,
o.RequiredDeliveryDate,
cp.PlanId,
cp.ClientPlanId
--c.ClientId
FROM
[Order] o
Inner Join ClientPlan cp on o.PlanId = cp.PlanId and o.CreatedByUserId = cp.UserId
Inner Join ClientUser c on o.CreatedByUserId = c.UserId
WHERE
--cp.ClientId = @ClientId
--AND
o.OrderDate BETWEEN @StartDate AND @EndDate
ORDER BY
o.OrderId DESC
END
ELSE
BEGIN
SELECT @SQLTEXT = 'Select
o.OrderId,
o.OrderDate,
o.CreatedByUserId,
c.LoginId,
o.Quantity,
o.RequiredDeliveryDate,
cp.PlanId,
cp.ClientPlanId
--cp.ClientId
FROM
[Order] o
Inner Join ClientPlan cp on o.PlanId = cp.PlanId --AND cp.ClientId in ('+ convert(Varchar, @ClientId) + ' )
Inner Join ClientUser c on o.CreatedByUserId = c.UserId
WHERE
cp.ClientId in (' + convert(Varchar,@ClientId) + ')
AND
o.OrderDate BETWEEN ''' + Convert(varchar, @StartDate) + ''' AND ''' + convert(varchar, @EndDate) + '''
ORDER BY
o.OrderId DESC'
exec(@SQLTEXT)
END





any help will be appreciated..

Thanks
Karen

View 14 Replies View Related

JDBC Error Incorrect Syntax Near '-'.

Sep 18, 2007

Hi I am using JDBC driver version "1.0.809.102". In the ms sqlserver 2000 database I am acessing there is a table named as "CDR_DATA_2007-09-12". When I run the following query "select * from CDR_DATA_2007-09-12" i get the following exception. Please help me out to solve this problem.

com.microsoft.sqlserver.jdbc.SQLServerException: Line 1: Incorrect syntax near '-'. at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerStatement.doExecuteStatement(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerStatement$StmtExecCmd.doExecute(Unknown Source) at com.microsoft.sqlserver.jdbc.TDSCommand.execute(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeQuery(Unknown Source) at Test.mssqldb(Test.java:80) at Test.main(Test.java:26) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:86)

Thanks,Gavin

View 3 Replies View Related

Server Error In '/' Application Incorrect Syntax Near ','.

Nov 20, 2006

This code used to work now I get an error(error follows code)  can anyone tell me where I went wrong?[vbcode]i = 0            For i = 0 To 7                If requests(i) <> "" Then                    request = requests(i)                    Dim sql1 As String = "insert request_items ([req_id],[request]) Select Case max(req_id), " & request & "  from(requests)"                    Dim myCommand1 As New SqlCommand(sql1, myConnection)                    myCommand1.ExecuteNonQuery()                Else                    Continue For                End If            Next[/vbcode] Server Error in '/' Application.

Incorrect syntax near ','.



Description: An
unhandled exception occurred during the execution of the current web
request. Please review the stack trace for more information about the
error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near ','.

Source Error:




Line 73: Dim sql1 As String = "insert request_items ([req_id],[request]) Select Case max(req_id), " & request & " from(requests)"Line 74: Dim myCommand1 As New SqlCommand(sql1, myConnection)Line 75: myCommand1.ExecuteNonQuery()Line 76: ElseLine 77: Continue For







Source File: C:InetpubloansMemberPagesRequest.aspx.vb    Line: 75


Stack Trace:




[SqlException (0x80131904): Incorrect syntax near ','.] System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +857242 System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +734854 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +188 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1838 System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async) +192 System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) +380 System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +135 Request.Button1_Click(Object sender, EventArgs e) in C:InetpubloansMemberPagesRequest.aspx.vb:75 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +105 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +107 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5102 

View 3 Replies View Related

ExecuteNonQuery() Throws An Incorrect Syntax Error

Apr 7, 2008

I try to update from datalist by using sqlcommand, it throws an error on the date field:
Mark up:

10/11/2008 12:00:00 AM        <--- the format in the SQL database
Error: 

System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near 'DOB'.Dim strSQL As String = _
"UPDATE [Customers] SET [country] = @country, " & _"[nickName] = @nickname, [identityid] = @identityid " & _
"[DOB] = @DOB, [Hpno] = @Hpno " & _"[address] = @address, = @email " & _
"WHERE [CustomerID] = @CustomerID"
...Dim parameterdob As SqlParameter = _
New SqlParameter("@DOB", SqlDbType.DateTime)
parameterdob.Value = Request.Form("txtdob") & " 00:00:00"
myCommand.Parameters.Add(parameterdob)
myCommand.ExecuteNonQuery()                                     <---  error here
...
<form id="form1" runat="server">
<asp:DataList ID="ProfileDataList" runat="server">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtdob" Text='<%#DataBinder.Eval(Container.DataItem, "DOB", "{0:d}")%>' />
</ItemTemplate>
</asp:DataList>

View 5 Replies View Related

COUNT Field Incorrect Or Syntax Error.

Sep 21, 2004

I'm stuck. This is in C#.
I am making the following query:
string query = INSERT INTO region_info(prefix, region, last_update) VALUES ('" + RegionInfo.Prefix + "', '" + region + "', ???TIMESTAMP???);

and then executing
query = query.Replace("???TIMESTAMP???", "'" + DateTime.Now.ToString("yyyyMMdd") + "'");

Thus, an example query is:
INSERT INTO region_info(prefix, region, last_update) VALUES ('907209', 'Alaska-Juneau', '20040921');
When I execute this query through my program(uses ADO.net), I get a "COUNT field incorrect or syntax error" exception, but if I run this same query through the query analyzer, it works fine.

Any ideas on what'z going wrong?
Thanks

View 5 Replies View Related

Error Creating Table - Incorrect Syntax

May 27, 2014

Have been given this code to create a table

CREATE TABLE 'emaillist' (
'id' INT(11) NOT NULL AUTO_INCREMENT,
'clientname' VARCHAR(200) NOT NULL DEFAULT '0',
'email' VARCHAR(200) NOT NULL DEFAULT '0',
PRIMARY KEY ('id')
);

when I execute it says

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'emaillist'.

What the correct code should be?

View 3 Replies View Related

.NET FW SDK QuickStart SQL-Express Error: Msg 102 ... Incorrect Syntax.

Aug 13, 2006

Hi,

I have followed the steps from the .NET FW SDK QuickStart Configuration (C:Program FilesMicrosoft Visual Studio 8SDKv2.0SamplesSetuphtmlConfigDetails.htm), and have got an error message trying to grant the ASP.NET User account access to the databases by the command sqlcmd -E -S (local)SQLExpress -Q "sp_grantlogin LEONEWASPNET" where LEONEW is my local machine name, and the ASPNET account exists in the Users group.

I am getting the error message: Msg 102, Level 15, State 1, Server LEONEWSQLEXPRESS, Line 1
Incorrect syntax near ''.

Please help if you know how to resolve this. Thanks in advance.

Alex.

View 5 Replies View Related

Transact SQL :: Error Incorrect Syntax Near Keyword Select

Apr 30, 2015

I am getting error "Incorrect syntax near the keyword 'Select'." while running the below query.

DECLARE @DATEPROCESS DATETIME;
SET @DATEPROCESS = CAST(DATEADD(D, -((DATEPART(WEEKDAY, GETDATE()) + 1 + @@DATEFIRST) % 7), GETDATE()) AS DATE)
insert into tempjoin([PART], [SPLRNAME], [SHIPDAYS], [SPRICE]) values
(Select distinct
RC. CAT_PART AS PART, 
RC. CAT_SUPPLIER AS SUPPLIER, 
FFC.[Ships Within Days] AS SHIPDAYS,
ffc.[Sell Price] AS SPRICE

[code]....

View 4 Replies View Related

Error Incorrect Syntax Near ',' When Exec Sql With Multi Value Parameter

Apr 3, 2008

I already used temptable, it works fine in SQL Server but doesn't work in Visual Studio. (it returns me "incorrect syntax near ',').

Here is my sql:


SET @sql = 'SELECT
RMI.Response_Date,
RMI.Master_Incident_Number,
RMI.Jurisdiction,
RVA.Radio_Name,
RVA.Response_Number,
RMI.Division,
RMI.Battalion,
RMI.Address,
RMI.Call_Disposition,
RMI.Cancel_Reason,
RMI.Problem,
RMI.Time_CallEnteredQueue,
RVA.Time_Enroute,
RVA.Time_ArrivedAtScene,
RG.Region,
RN.District ' +
' INTO RPT_PRIME_JOB_DTL ' +
' FROM ' + @server_name + 'Response_Master_Incident RMI ' +

'LEFT OUTER JOIN ' + @server_name + 'Response_Vehicles_Assigned RVA
ON RMI.ID = RVA.Master_Incident_ID ' +

'LEFT OUTER JOIN AKSDCSVR01.CAD_Lookup_Tables.dbo.Radio_Name RN
ON RVA.Radio_Name = RN.Radio_Name Collate SQL_Latin1_General_CP1_CI_AS ' +

'LEFT OUTER JOIN AKSDCSVR01.CAD_Lookup_Tables.dbo.Region RG
ON RMI.Jurisdiction = RG.Jurisdiction Collate SQL_Latin1_General_CP1_CI_AS ' +

'WHERE ' +
' RG.Region = ''' + @region + '''' +
' AND RN.District IN (SELECT Item FROM dbo.StringArrayIntoTable(''' + @district + ''', '','') ' +
' AND (RMI.response_date >= ''' + CONVERT(VARCHAR(10), @date_from,111) + '''' +
' AND RMI.response_date <''' + CONVERT(VARCHAR(10),@date_to+1,111) + ''')' +
' AND RVA.Radio_Name LIKE ''PD%'''

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
EXEC (@sql)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
SELECT *
FROM RPT_PRIME_JOB_DTL


Thank

View 3 Replies View Related

T-SQL Error In Creating A Stored Procedure That Has Three Parameters: Incorrect Syntax Near 'WHERE'

Feb 17, 2008

Hi all,

I copied the the following code from a book to the query editor of my SQL Server Management Studio Express (SSMSE):
///--MuCh14spInvTotal3.sql--///
USE AP --AP Database is installed in the SSMSE--
GO
CREATE PROC spInvTotal3
@InvTotal money OUTPUT,
@DateVar smalldatetime = NULL,
@VendorVar varchar(40) = '%'
AS

IF @DateVar IS NULL
SELECT @DateVar = MIN(InvoiceDate)

SELECT @InvTotal = SUM(InvoiceTotal)
FROM Invoices JOIN Vendors
WHERE (InvoiceDate >= @DateVar) AND
(VendorName LIKE @VendorVar)
GO
///////////////////////////////////////////////////////////////
Then I executed it and I got the following error:
Msg 156, Level 15, State 1, Procedure spInvTotal3, Line 12
Incorrect syntax near the keyword 'WHERE'.
I do not know what wrong with it and how to correct this problem.

Please help and advise.

Thanks,
Scott Chang

View 18 Replies View Related

Incorrect Syntax Near The Keyword 'EXEC' (Dynamic Sql Statement Error)

Nov 1, 2007

Following is the stored procedure iam trying to create.Here i am trying to

First create a table with the table name passed as parameter
Second I am executing a dynamic sql statement ("SELECT @sql= 'Select * from table") that returns some rows.
Third I want to save the rows returned by the dynamic sql statement ("SELECT @sql= 'Select * from table") in the tablei created above.All the columns and datatypes are matching.

This table would be further used with cursor.
Now i am getting a syntax error on the last line.Though i doubt whether the last 3 lines will execute properly.Infact how to execute a sp_executesql procedure in another dynamic sql statement.ANy suggestions will be appreciated.


CREATE PROCEDURE [dbo].[sp_try]

@TempTable varchar(25)


AS

DECLARE @SQL nvarchar(MAX)

DECLARE @SQLINSERT nvarchar(MAX)



BEGIN


--create temp table

SELECT @Sql= N'CREATE TABLE ' + QUOTENAME(@TempTable) +

'(

ContactName varchar (40) NOT NULL ,

ContactId varchar (30) NOT NULL ,

ContactrMessage varchar (100) NOT NULL,



)'

EXEC sp_executesql @Sql, N'@TempTable varchar(25)', @TempTable = @TempTable


SELECT @sql= 'Select * from table'




SELECT @sqlinsert = 'INSERT INTO ' + quotename( @TempTable )

SELECT @sqlinsert = @sqlinsert + EXEC sp_executesql @sql, N'@Condition varchar(max)', @Condition=@Condition

EXEC sp_executesql @SQLINSERT, N'@TempTable varchar(25)', @TempTable = @TempTable

View 8 Replies View Related

Receiving Error 156 - Incorrect Syntax When Compiling Stored Procedure

May 14, 2008

The following query works fine in query analyzer, but when I add it to my stored procedure I receive an error 156. How do I work around this?

select distinct(dateposted)
from billingprocedures bp1,
billingprocedureordercomponentvalues bpocv,
ordercomponentvalues ocv
where bp1.billingid = @billingid
and bp1.procedureid = bpocv.billingprocedureid
and bpocv.ordercomponentvalueid = ocv.ordercomponentvalueid

Thanks,
Bryan

View 12 Replies View Related

Multi-Value Parameter Error: Incorrect Syntax Neat The Keyword Else

Dec 11, 2007

Hi all,

Could someone please help me!!! I am using a multi-value parameter in SQL 2005 reports and am getting the following error message:


An error has occured during report processing.
Qiery execution failed for dataset
an expression of non-boolean type specified in a context where condition is expected, near ','
Incorrect syntax near keyword else.

The multi-value parameter works when it isn't run in the if, else clause i checked the where clause with a single paramter and it works OK. I don't understand what is causing this problem but I really need to fix it. Here is my query.

if @job_SubRep_ProjNo_param = '0'

Begin
select Job_Job_No as job, Job_Job_Name as Job_title,
cast(Job_Total_Fee as float) as fee,
employee_first_name + ' ' + employee_surname as jl_name,
cast(Job_Percent_Complete as float) as percentcomplete,
cast(Job_Work_Done as float) as workdone,
cast(Job_Invoicing as float) as job_Invoicing,
job_WIP,
Job_Expenditure as timecost,
job_project_no,
Job_Profit_Loss,
cast(Job_Hours as float) as hours,
job_expenses
from job_tbl
inner join project_tbl on job_project_no = project_no
inner join employee_tbl on job_jl_empno = employee_no
where project_pl_empno = @pl_employeeNo or job_jl_empno = @jl_subRep

end
else
select Job_Job_No as job, Job_Job_Name as Job_title,
cast(Job_Total_Fee as float) as fee,
employee_first_name + ' ' + employee_surname as jl_name,
cast(Job_Percent_Complete as float) as percentcomplete,
cast(Job_Work_Done as float) as workdone,
cast(Job_Invoicing as float) as job_Invoicing,
job_WIP,
Job_Expenditure as timecost,
job_project_no,
Job_Profit_Loss,
cast(Job_Hours as float) as hours,
job_expenses
from job_tbl
inner join project_tbl on job_project_no = project_no
inner join employee_tbl on job_jl_empno = employee_no
where job_project_no in (@job_SubRep_ProjNo_param) or job_jl_empno = @jl_subRep

Thanks in advance!!

Katie

View 7 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved