Transact SQL :: Getting Syntax Errors In Where Statement
Oct 9, 2015
I've created multiple select statement to pull in varies fields from a table and one of those fields is Fiscal_Year, however, after the select statement I'm adding a Where clause:
I keep receiving the following error whenever I try and call this function to update my database.
The code was working before, all I added was an extra field to update.
Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'WHERE'
Public Sub MasterList_Update(sender As Object, e As DataListCommandEventArgs)
Dim strProjectName, txtProjectDescription, intProjectID, strProjectState as String Dim intEstDuration, dtmCreationDate, strCreatedBy, strProjectLead, dtmEstCompletionDate as String
Dim myConnection As New SqlConnection(System.Configuration.ConfigurationSettings.AppSettings("connectionstring")) Dim cmdSQL As New SqlCommand(strSQL, myConnection)
Hi Dears Below is the Sp that i want to use but there are many Syntax erros plz verify and correct them Thnx
create procedure CheckStatus
@EmpID int as -- i need some variables so i declared them declare @ShiftId int declare @DayTime smalldatetime declare @ShiftStartT smalldatetime declare @ShiftEndT smalldatetime declare @ShiftInOutStatus int declare @ShiftValidity bit declare @RTValue int
-- Now i m assigning the values to the declared variable by selecting some value from tables -- from this point i m having syntax erroes i dont know what are they all atables and all fields are ok verified
set @ShiftId=SELECT S_Id FROM Emp_Info WHERE Emp_Info.Emp_Id=@EmpID set @DayTime=SELECT GETDATE() set @ShiftStartT=SELECT S_ST FROM Emp_Shift WHERE Emp_Shift.S_Id=@ShiftId set @ShiftEndT=SELECT S_ET FROM Emp_Shift WHERE Emp_Shift.S_Id=@ShiftId set @InOutStatus=SELECT IOStatus FROM Emp_Status WHERE Emp_Status.Emp_Id=@EmpId -- here i m using a nested case for some checks to insert values into tables CASE -- Main Case WHEN @InOutStatus=0 OR @InOutStatus=-1 -- Calling udf_IsShiftValid(datetime,datetime,datetime) a function that ia also ok and returns two possible value 0 or 1 THEN @ShiftValidty=udf_IsShiftValid(@ShiftStartT,@ShiftEndT,@DayTime) CASE --nested case starts here WHEN @ShiftValidity=1-- Insertin value into Emp_Status table and assihning value to @RTValue THEN (INSERT INTO Emp_Status(IOStatus) VALUES(@ShiftValidity) WHERE Emp_Status.Emp_Id=@EmpID SET @RTValue=1) WHEN @ShiftValidity=0 THEN SET @RTValue=-1 END-- Nested case End Here WHEN @InOutStatus=1 THEN INSERT INTO Emp_Status(IOStatus) VALUES(0) WHERE Emp_Status.Emp_Id=@EmpID SET @RTValue=0 END
Select Sum(Cost) as Cost, Case When PymtRmID = 'Net 10' then (TodaysDate)+10 else pymtrmid end From #ttNonWires Group By Case When PymtRmID = 'Net 10' then (TodaysDate)+10 else pymtrmid end
Im trying to show obviousally when something when PYMTRMID says net10 i want todaydate +10 days in the column next to it i keep getting
Server: Msg 241, Level 16, State 1, Line 1 Syntax error converting datetime from character string.
SET @Test1 = N'select * from table1 where column1 in (' + @Test + ')'
EXEC sp_executesql @Test1
If I put it in a "Begin Transaction" block
there is a syntax error near the ( in the set @Test1 statement.
If I leave it out of a "Begin Transaction" Block,
The syntax error is:
Server: Msg 105, Level 15, State 1, Line 1 Unclosed quotation mark before the character string ''. Server: Msg 170, Level 15, State 1, Line 1 Line 1: Incorrect syntax near ''.
create proc dbo.sp_GetInvitationsHistoryDetails(@ExecID int, @OrgID int) as IF (@OrgID = 0) BEGIN select E.EventID,E.Description as Event,E.EventDate as Date I.Attending as [Att'g],NotAttending as [Not att'g],I.Bootcamp as [Maybe] I.Attended FROM Invitations I INNER JOIN Events E on I.EventID=E.EventID WHERE I.MemberID=@ExecID and NotForStats=0 ORDER BY E.EventDate DESC END ELSE BEGIN select E.EventID,E.Description as Event,E.EventDate as Date count(*) as Invited,SUM(CONVERT(smallint,I.Attended)) AS Attended FROM Invitations I INNER JOIN Events E on I.EventID=E.EventID WHERE I.MemberID IN (select ID FROM Executives WHERE OrganisationID=OrgID GROUP BY E.EventID,E.Description,E.EventDate ORDER BY E.EventDate DESC END
and i'm getting the following syntax errors when i check it -
Msg 102, Level 15, State 1, Procedure sp_GetInvitationsHistoryDetails, Line 10
Incorrect syntax near 'I'.
Msg 102, Level 15, State 1, Procedure sp_GetInvitationsHistoryDetails, Line 19
Incorrect syntax near 'count'.
Msg 156, Level 15, State 1, Procedure sp_GetInvitationsHistoryDetails, Line 23
Incorrect syntax near the keyword 'ORDER'.
Originally i just ran this sql from C# and it worked, obviously added the @ to the variables but it's basically the same.
How to alter all objects in database i want to find if can any syntax errors in my database after restoring from sql 2008 to 2012. I Can create as test and drop them but trying to find a way to alter proc , views and functions..
I am having a problem registering any WMI Event in the ootMicrosoftSqlServerServerEvents namespace on all of my SQL Servers. It doesn't matter what instance I append behind this either. MSSQLSERVER fails as will any other named instance. I get the same exact errors on every server which isn't surprising since they currently all have identical configurations, excluding hardware:
"The @wmi_query could not be executed in the @wmi_namespace provided. Verify that an event class selected in the query exists in the namespace and that the query has the correct syntax."and it doesn't apply because my servernames are all 8 characters long, and I already applied CU6 to the servers months ago. The current @@Version on all Servers is:
Microsoft SQL Server 2005 - 9.00.3233.00 (X64) Mar 6 2008 21:58:47 Copyright (c) 1988-2005 Microsoft Corporation Enterprise Edition (64-bit) on Windows NT 5.2 (Build 3790: Service Pack 2)
the only differece is that some of them are x86 instead of X64, but the problem occurs on the x86 servers as well.What is interesting is I can register other WMI namespaces just fine, like the following from Jason Massies Blog:
EXEC msdb.dbo.sp_add_alert @name =N'Test', @enabled =1, @delay_between_responses =0, @include_event_description_in =0, @wmi_namespace =N'.ROOTCIMV2', @wmi_query =N'SELECT * FROM __InstanceModificationEvent WITHIN 600 WHERE TargetInstance ISA "Win32_LogicalDisk" AND TargetInstance.FreeSpace < 100000' GO
I can create the WMI Alert on my laptop which is build 3054.
select row_number() over (partition by merrickid order by recorddate asc) as rn, merrickid, recorddate, allocestgasvolmcf, sum(allocestgasvolmcf) over (partition by merrickid order by recorddate asc) as xxxxxxxx from dbo.completiondailytb where merrickid=1965
I get the following message after I insert the sum() over function:
Msg 102, Level 15, State 1, Line 5 Incorrect syntax near 'order'.
Hi, I created a sqldatasource (sql server) and a gridview.In the aspx file, i can see the selectcommand: SelectCommand="select email from mytable" Now, i want to modify something in the selectcommand produced in the aspx file, in order to get the emails in clickable mode. I knwow i have to add a string like: <a hef="mailto:mailaddress">mailadress</a> So i tried this: SelectCommand="select '<a href="mailto:'+ email +'">' , email + '</a>' from email But this gives the error: "tag is not well formed".The problem is the " around mailto: Thanks Cl.
Here is an sql query but it keeps giving me an error of (Incorrect syntax near keywork ON) here is the sql, don't get why this doe not work when I have done it this way multiple times. select DISTINCT c.strSSN, p.sidstrNAME_IND, p.sidstrGR_ABBR_CODE, p.sidstrSSN_SM, p.sidstrST_ADDR, p.sidstrADDR_CITY, p.sidstrSTATES_US, p.sidstrZIP_CODE, p.sidstrPAY_GR, p.sidstrMARTL_STAT, p.sidstrNBR_EXEMPT, p.sidstrST_TAX_CODE, u.lsdbstrPHONE_NBR_HOME, case when sidstrTech_SVC_Code in ('M', 'R', 'S', 'T', 'U', 'Z') then case when sidstrACT_STAT_PROG in ('5', 'A', 'E', 'F', 'N', 'R', 'S', 'T') then 'AGR' else 'Tech' end else 'M-Day' end as status from tblAssignedPersonnel as c on ap.strssn = p.sidstrSSN_SM Inner Join cms.dbo.tblLSDB as u on u.lsdbstrSSN_SM = c.strSSN inner joincms.dbo.tblSidpers as p on ap.strSSN = p.sidstrSSN_SM where intUICID = (select intUICID from tblUIC where strUIC = '2' and intTaskForceID = '1') order by p.sidstrNAME_IND
I am trying to write a SQL Server query that archives x-days old data from [Archive].[TestToDelete] to [Working].[TestToDelete]table. I want to check that if the records on ArchiveTable do not exist then insert then deleted...which will be converted to a proc later.. archives x-days old data from [Working].[TestToDelete] to [Archive].[TestToDelete] table */Here is the table definition, it is the same for both working and archive tables. There are indexes on: IpAddress, Logdate, Server, User and Sysdate (clustered).
CREATE TABLE [Archive].[TestToDelete]([Server] [varchar](16) NOT NULL,[Logdate] [datetime] NOT NULL,[IpAddress] [varchar](16) NOT NULL,[Login] [varchar](64) NULL,[User] [varchar](64) NULL,[Sysdate] [datetime] NULL,[Request] [text] NULL,[Status] [varchar](64) NULL,[Length] [varchar](128) NULL,[Referer] [varchar](1024) NULL,[Agent] [varchar](1024) NULL) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]/* the syntax, which will be converted to proc is: */SET NOCOUNT ON;DECLARE @Time DATETIME,@R INT,@ErrMessage NVARCHAR(1024)SET @R = 1/* set @Time to one day old data */SET @Time =
I'm a Power Builder (PB) developer. I've migrated PB from 10 .5 to 12.5, and now I need to migrate the stored procedures from SQL Server 2005 to 2012 as well.I get a invalid expression error when I run the procedures in Power Builder. We have previously been using a lower database compatibility model in 2005, which allowed the procedures to work there. I have learned that =* is the old way to write right outer joins.
For example: select * from A right outer join B
[code]...
Is my approach correct, or do I need to add a WHERE condition to it? I don't have access to the production database to check. The development database is in SQL Server 2012 too, sO I will not be able to run the old version there to check.
SELECT APHIST.ReturnDate AS ATDATE ,API_HIST.[ActionPlanItemID] ,API_HIST.[ActionPlanID] ,PIT.[ProductItemID] ,PIT.ProductItemCode ,PIT.Name,
[Code] ....
That query is suppose to add to calculation field OutStock and InStock based on the value of n
When executing this query I get the following message :
Column 'Sales.ActionPlan_History.ReturnDate' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
I need to use IF-THEN in a SQL Select statement. Using Google I have found a couple of obscure references to this but nothing that I can use. Tried various combinations without luck. Can anyone point me to a good resource or supply a simple example of proper syntax? Thanks in advance for any help provided.
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString2"].ToString()); SqlCommand myCommand = new SqlCommand("SELECT (Deadline, Description, Headline, AddressField, OrganizationField, NameField, FileField, EmailField, CommentField) FROM RegistrationFormDB_Info WHERE (UserName = @UserName AND TournamentName = @TournamentName)", myConnection); SqlParameter myParam = new SqlParameter(); myParam.ParameterName = "@UserName"; myParam.Value = User.Identity.Name; myCommand.Parameters.Add(myParam); myParam = new SqlParameter(); myParam.ParameterName = "@TournamentName"; myParam.Value = Request.QueryString["TournamentName"]; myCommand.Parameters.Add(myParam); myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); <====================== I continue to get this error and I can't figure out the problem! Anything helps. Thank you very much.
I have the following statement that I am trying to convert to a "like" statement in a SqlDataSource for a web application. I can't seem to get the syntax correct. Would someone be able to assist with this? Thanks! SELECT * FROM [Employees] WHERE ([LName] = @LName) ORDER BY [LName], [FName] Something like below. SELECT * FROM [Employees] WHERE ([LName] LIKE '@LName%') ORDER BY [LName], [FName]
SELECT DISTINCT CONVERT (nvarchar , tblSubject.Subject, 108) AS SubjectTime, CONVERT (nvarchar(11), tblSubject.Subject, 100) AS Date FROM tblLooker,tblSubject,tblStop WHERE NOT (SELECT DISTINCT CONVERT (nvarchar , tblSubject.Subject, 108) AS SubjectTime, CONVERT (nvarchar(11), tblSubject.Subject, 100) AS Date FROM tblSubject, tblLooker, tblStop WHERE tblSubject.Subject > tblLooker.Looker AND tblSubject.Subject < tblStop.Stop AND tblLooker.id = tblStop.id) Msg 170, Level 15, State 1, Line 5Line 5: Incorrect syntax near ')'. Can anyone tell me why this is not working? Thanks
What is the syntax for making a query using like, the below is my code <asp:SqlDataSource ID="Search" runat="server" ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString %>" ProviderName="<%$ ConnectionStrings:DatabaseConnectionString.ProviderName %>" SelectCommand="SELECT * FROM [Products]WHERE category LIKE %@category%">
<SelectParameters> <asp:QueryStringParameter Name="category" QueryStringField="category" Type="string" /> </SelectParameters> </asp:SqlDataSource> Its giving a syntax error but I dont know how to change it. Please advise, thanks!
I am a java developer having little bit knowledge in sql statements. can any body guide me what is the effective way of using sql statement to achieve the following goal.
here is the requirement.
1. There are 2 tables A & B.
2.The table 'B' may or maynot have an equivalent entry for the primary key of table a.
3. select column1 (of A), column 2(of B) from table a and b.
4. now column2 should give a value, if there is a corresponding entry in table b.other wise null.
5. at any time there may be 0 to 1 record in table b for the primary of table a.
Can someone tell me what is wrong with my syntax? I am getting several errors:
Incorrect syntax near keyword 'CASE' Incorrect syntax near keyword 'WHEN'
Incorrect syntax near '@Tablename'
CREATE PROCEDURE al_readcampsignup
@User_ID int,
@Pagenumber smallint,
@Tablename varchar(10)
AS
CASE @Mypagenumber WHEN 1 THEN SELECT Blah FROM tempcampsignup WHERE Camp_ID = @User_ID WHEN 2 THEN SELECT Blah FROM @Tablename WHERE Camp_ID = @User_ID WHEN 3 THEN SELECT Blah FROM @Tablename WHERE Camp_ID = @User_ID END
I inherited a query and I am getting an error of Unsupported literal in join in the INNER JOIN FRDM.dbo.MEMBER_SUBSC FRDM_dbo_MEMBER_SUBSC2
ON (frdm.dbo.CLAIM_HEADER_WITH_VOIDS_VIEW.SBSB_CK = FRDM_dbo_MEMBER_SUBSC2.SBSB_CK AND FRDM_dbo_MEMBER_SUBSC2.MEME_SFX = '00')statement. Specifically the AND FRDM_dbo_MEMBER_SUBSC2.MEME_SFX = '00')part. SELECT frdm.dbo.CLAIM_HEADER_WITH_VOIDS_VIEW.GRGR_ID AS 'group number'
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.
Hi,I'm new to SQL Server Programming, I work with ASP a lot, but latelyI've been trying to create Stored Procedures, etc. I'm having aproblem writing a simple IF statement.. I don't seem to understand whyit's giving me this error. I've search around on Google Groups, but Istill don't get it.=================USE msdbIF NOT EXISTS (SELECT * FROM sysjobs WHERE name = 'Scheduled Nightfax')END=================My error is:Server: Msg 156, Level 15, State 1, Line 5Incorrect syntax near the keyword 'END'.Thanks for any help.
I am trying to take all the trips that equal a one and divide them by the total number of service calls and then multiple them by 100 to get the percentage.
I am receiving the following errror: "The value expression refers to the field 'SvcCallNumber'. Report item expressions can only refer to fields within the current dta set scope or, if inside an aggregate, the specified data set scope...