I have a basic StoredProcedure that I want to raise a custom error if the inserted data is already in the table. However, I'm getting a Syntax error "User has already been entered".
Code Snippet
ALTER PROCEDURE dbo.sp_AddParticipant
(
@pLanID as varchar(20),
@pName as varchar(75),
@pTeamID as numeric,
@pDept as varchar(35),
@pEmail as varchar(75),
@pUpdater varchar(20),
@pParticipantID numeric OUTPUT
)
AS
SET NOCOUNT ON
if exists (SELECT LANID FROM Participant WHERE LANID = @pLanID)
raiserror("User has already been entered",16,1)
else
begin
INSERT INTO Participant
(LANID,Name,TeamID,Department,eMailAdd,LastUpdatedBy)
VALUES
(@pLanID,@pName,@pTeamID,@pDept,@pEmail,@pUpdater);
SELECT @pParticipantID = @@Identity;
end
RETURN
As far as I can see, I have the raiserror correct but I don't see what's wrong with the previous line.
Does anyone see what I'm missing?
Thanks, Bill N
P.s. What is the better method, passing an Out parameter or saying "RETURN @@Identity"?
I am testing a simple stored proc below. create procedure procpooh @val1 int, @val2 int as insert into pooh (val1, val2) values(@val1,@val2) declare @error int SELECT @error = @@ERROR IF @error <> 0 BEGIN print 'it failed' RAISERROR(50020,16,1,@error) end
When I run the proc and feed it the values it fails(that' what I expect) because there is a field not being supplied which will not allow nulls. However neither the print ' it failed ' or the raiserror work. I get the message below instead. Any ideas why the print or raiserror don't work? Server: Msg 515, Level 16, State 2, Procedure trpooh, Line 11 Cannot insert the value NULL into column 'val3', table 'Chapter5DB.dbo.pooh2'; column does not allow nulls. INSERT fails. The statement has been terminated.
My C# asp.net web application is throwing an exception and the message is the following:
RAISERROR could not locate entry for error 60002 in sysmessages. The error occurs in the stored procedure. Can anyone tell me what I need to do to fix this problem? Note that if I manually run the stored procedure, I get the following error message: Msg 2758, Level 16, State 1, Procedure GetPortalSettings, Line 74 RAISERROR could not locate entry for error 60002 in sysmessages.
i have migrated a DTS package wherein it consists of SQL task.
this has been migrated succesfully. but when i execute the package, i am getting the error with Excute SQL task which consists of Store Procedure excution.
But the SP can executed in the client server. can any body help in this regard.
Hi, all I'm getting this error at runtime when my page tries to populate a datagrid. Here's the relevant code. First, the user selects his choice from a dropdownlist, populated with a sqldatasource control on the aspx side:<asp:SqlDataSource ID="sqlDataSourceCompany" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [PayrollCompanyID], [DisplayName] FROM [rsrc_PayrollCompany] ORDER BY [DisplayName]"> </asp:SqlDataSource> And the dropdown list's code:<asp:DropDownList ID="ddlPayrollCompany" runat="server" AutoPostBack="True" DataSourceID="sqlDataSourcePayrollCompany" DataTextField="DisplayName" DataValueField="PayrollCompanyID"> </asp:DropDownList> Then, I use the selectedindexchanged event to bind the data to the datagrid. Here's that code: 1 Sub BindData() 2 3 Dim ds As New DataSet 4 Dim sda As SqlClient.SqlDataAdapter 5 Dim strSQL As String 6 Dim strCon As String 7 8 strSQL = "SELECT [SocialSecurityNumber], [Prefix], [FirstName], [LastName], [HireDate], [PayrollCostPercent], " & _ 9 "[Phone], [BadgeNumber], [IsSupervisor], [SupervisorID], [IsUser], [IsScout] FROM [rsrc_Personnel] " & _ 10 "WHERE ([PayrollCompanyID] = @PayrollCompanyID)" 11 12 strCon = "Data Source=DATASOURCE;Initial Catalog=DATABASE;User ID=USERID;Password=PASSWORD" 13 14 sda = New SqlClient.SqlDataAdapter(strSQL, strCon) 15 16 sda.SelectCommand.Parameters.Add(New SqlClient.SqlParameter("@PayrollCompanyID", Me.ddlPayrollCompany.SelectedItem.ToString())) 17 18 sda.Fill(ds, "rsrc_Personnel") 19 20 dgPersonnel.DataSource = ds.Tables("rsrc_Personnel") 21 dgPersonnel.DataBind() 22 23 End Sub 24
I'm assuming my problem lies in line 16 of the above code. I've tried SelectedItemIndex, SelectedItemValue too and get errors for those, as well. What am I missing? Thanks for anyone's help! Cappela07
Hi, I'm having an SSIS package which gives the following error when executed :
Error: 0xC002F210 at Create Linked Server, Execute SQL Task: Executing the query "exec (?)" failed with the following error: "Syntax error or access violation". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.Task failed: Create Linked Server
The package has a single Execute SQL task with the properties listed below :
General Properties Result Set : None
ConnectionType : OLEDB Connection : Connected to a Local Database (DB1) SQLSourceType : Direct Input SQL Statement : exec(?) IsQueryStorePro : False BypassPrepare : False
Parameter Mapping Properties
variableName Direction DataType ParameterName
User::AddLinkSql Input Varchar 0
'AddLinkSql' is a global variable of package scope of type string with the value Exec sp_AddLinkedServer 'Srv1','','SQLOLEDB.1',@DataSrc='localhost',@catalog ='DB1'
When I try to execute the Query task, it fails with the above error. Also, the above the sql statement cannot be parsed and gives error "The query failed to parse. Syntax or access violation"
I would like to add that the above package was migrated from DTS, where it runs without any error, eventhough it gives the same parse error message.
I would appreciate if anybody can help me out of this issue by suggeting where the problem is.
Hi All, can someone help me, i've created a stored procedure to make a report by calling it from a website. I get the message error "241: Syntax error converting datetime from character string" all the time, i tryed some converting things but nothig works, probably it is me that isn't working but i hope someone can help me. The code i use is:
CREATE proc CP_Cashbox @mID varchar,@startdate datetime,@enddate datetime as set dateformat dmy go declare @startdate as varchar declare @enddate as varchar
--print "query aan het uitvoeren"
select sum(moneyout) / sum(moneyin)*100 as cashbox from dbo.total where machineID = '@mID' and njdate between '@startdate' and '@enddate' GO
ALTER TABLE [dbo].[CalCalendar] ALTER COLUMN [OID] uniqueidentifier NOT NULL PRIMARY KEY NONCLUSTERED
is answered with:
Server: Msg 156, Level 15, State 1, Line 2 Incorrect syntax near the keyword 'PRIMARY'.
which I consider to be interesting. Anyone has an idea why? I checked documentation but I do not see an error.
Note that:
ALTER TABLE [dbo].[CalCalendar] ALTER COLUMN [OID] uniqueidentifier NOT NULL
DOES get executed, and
ALTER TABLE [dbo].[CalCalendar] ALTER COLUMN [OID] uniqueidentifier NOT NULL PRIMARY KEY
produces the same error.
Now, in my understanding this has nothing to do with an index may already exist etc. - the eror indicates a SYNTAX error, before any checking. Makes no sense to me, though, reading the documentation.
Hi, I'm writing a stored procedure and when I click on the Check Syntax button its giving me the error in the subject. I'm not really sure whats wrong with this. Here is my Stored Procedure code. Any help wud be appreciated.
In my Windows application I use sqlCmd.ExecuteNonQuery() to execute the stored procedure, In case of an error in the stored procedure I need to return an exception to application, will RAISERROR in stored procedure accomplish that?
Hello,I am raising an error on my SQL 2005 procedure as follows: RAISERROR(@ErrorMessage, @ErrorSeverity, 1)How can I access it in my ASP.NET code?Thanks,Miguel
hi RAISERROR is used to return message to the caller. how to contain RAISERROR : variable declare @name varchar(50) and string 'Welcome' i want to contain the RAISERROR messege 'Welcome' + @name value in the same time ex Welcome Zaid can give the code to do this thank you
just cant figure out why my raiserror print Wrong RoleType for customer lientID for :- RAISERROR('Wrong RoleType for customer %ClientID', 16,1, @ClientID) what's with missing C? is % some kind of escape char or something? (im trying to print back the parameter @clientid), or should i just use the print ''
This statement adds a new message to the master..sys.messages table
EXEC sp_addmessage @msgnum = 60000, @severity = 16, @msgtext = N'The item named %s already exists in %s.'
But if this error happens, how is an application supposed to access this message? (The average app shouldn't need to access to the master database to get this info.)
In my Windows application I use sqlCmd.ExecuteNonQuery() to execute the stored procedure, In case of an error in the stored procedure I need to return an exception to application, will RAISERROR in stored procedure accomplish that?
Hi Guys, I'm hoping somebody can help me with this really frustrating problem that I'm having....... I'm developing a peer to peer file sharing application (final year degree project) in which I use a web service & sql database as the management server. For some strange reason, I'm getting an SQL syntax error on some machines but not on others when I call the method to submit a file list to the server (see below for code for the method). Another strange thing is that on different machines, I'm getting a different error. I've seen "incorrect syntax near 'd' ". and also "incorrect syntax near 've' ", while on two other machines it works just fine - It appears that the connection to the webservice and to the database is working just fine on all machines as before this method I have a login which works perfectly and the data is represented in the database. Does anybody have any pointers or even the slighest idea what can cause an error like this or have seen anything like this before. Hoping to get this sorted pretty soon as the deadline is nearing. All and any help is very much appreciated!!!! Kevin public void submitFiles(FileObject[] files, string peerID) { foreach (FileObject fo in files) { System.Text.StringBuilder submit = new System.Text.StringBuilder("INSERT INTO SharedFiles (FileID, FileName, FileType, FileSize, PeerID) VALUES ('" + fo.guid.ToString() + "', '" + fo.name + "' ,'" + fo.name + "', '" + fo.size + "', '" + peerID + "')"); SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(submit.ToString(), con); try { con.Open(); cmd.ExecuteNonQuery(); } finally { con.Close(); } } }
Hello, I have this sql quiery: sqlcommand2.CommandText = "Select Count(UserIP) From InboundTraffic Where InboundURL Contains('" & SiteDomain(i).ToString & "') and DateTimeReceived > " & Last30Days
SiteDomain is placing a string variable such as website.com and Last30Days is a date variable which = now - 30days Im getting this error "Syntax error (missing operator) in query expression 'InboundURL Contains('website.com') and DateTimeReceived > 7/9/2007 8:20:30 PM'"
Could someone help me with this error message: Syntax error converting the varchar value '180 Ways to Walk the Leadership Talk by John Baldoni' to a column of data type int. Getting error on the Titles.title column. Tried casting it but it still does not work. What am I missing? CREATE procedure GetRequestInfo@Requestorid int ASselect distinct requestors.Requestorid, CAST(Titles.title AS VARCHAR(255)), requestors.requestorEmail,Requestors.requestdate, fname, lname, phonenum,StreetAddress1, City, State, Zip,LibraryRequest.ShipDate,LibraryRequest.DueDate,LibraryRequest.ReturnDate, Cast(DATEPART(m, requestors.requestDate) as Varchar(5)) + '/' +Cast(DATEPART(d, requestors.requestDate) as Varchar(5)) + '/' + Cast(DATEPART(yy, requestors.RequestDate) as Varchar(5)) as 'RequestDate' from Requestorsjoin Titles on titles.Titleid = requestors.Titleidjoin libraryRequest on LibraryRequest.Titleid = LibraryRequest.Titleidwhere Requestors.requestorid = requestors.requestoridGO
Can anyone tell me why I get a syntax error on the THEN and the ELSE? @Start datetime,@End datetime,@EmailAck bit,@SelectedProcess nvarchar(25)ASBEGINIF @SelectedProcess = 'Monthly' THENUPDATE tblReminderSchedule SETPrintedDate=GETDATE(),[Status]=1FROM tblReminderSchedule INNER JOIN tbllOAN ON tblReminderSchedule.lOAN_ID = tbllOAN.lOAN_IDWHERE (tblReminderSchedule.ReminderDate BETWEEN @Start AND @End) AND (dbo.tblReminderSchedule.ReceivedDate IS NULL) AND (tbllOAN.ReminderByEmail = @EmailAck) AND (tbllOAN.Frequency = 'Monthly')ELSEUPDATE tblReminderSchedule SETPrintedDate=GETDATE(),[Status]=1FROM tblReminderSchedule INNER JOIN tbllOAN ON tblReminderSchedule.lOAN_ID = tbllOAN.lOAN_IDWHERE (tblReminderSchedule.ReminderDate BETWEEN @Start AND @End) AND (dbo.tblReminderSchedule.ReceivedDate IS NULL) AND (tbllOAN.ReminderByEmail = @EmailAck) AND (tbllOAN.Frequency <> 'Monthly')END
I am trying to open a table in my DB to check for login ids:
The code I used is below> I will appreciate any help on this matter
<CODE> Public Function Authorize(ByVal Username As String, ByVal Password As String) As Integer Dim sql As String Dim con As New SqlConnection("data source=localhost; initial catalog=Jasist; Integrated Security = SSPI") sql = "Select * from USER Where User_Name = '" & Username & "' and User_Passwd = '" & Password & "'" con.Open() Dim cmd As New SqlCommand(sql, con) Dim Id1 As Integer Dim dr As SqlDataReader = cmd.ExecuteReader If dr.Read Then Id1 = 1 con.Close() dr.Close() Return Id1 Else con.Close() dr.Close() Return 0 End If End Function <CODE>
THE ERROR GENERATED WAS->
Server Error in '/Jasist' Application. --------------------------------------------------------------------------------
Incorrect syntax near the keyword 'USER'. 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 the keyword 'USER'.
Source Error:
Line 19: con.Open() Line 20: Dim cmd As New SqlCommand(sql, con) Line 21: Dim Id1 As Integer Line 22: Dim dr As SqlDataReader = cmd.ExecuteReader Line 23:
-------------------------------------------------------------------------------- Version Information: Microsoft .NET Framework Version:1.1.4322.573; ASP.NET Version:1.1.4322.573
Hi, hope someone can spend a minute checking out my script error. The following is part of my SQL statement. It has got syntax error near "=" I was hoping the script could run 100 times and print number 1 to 100.
DECLARE @ID int SET @id = 1 EXEC (' WHILE ' + @id + ' <= 100 ' + ' BEGIN SELECT ' + @id + ' SET ' + @id + ' = ' + @id + ' + 1 ' + ' END ' )
hi i am getting this error while running SQL query : syntax error near '='
Query is :
SELECT People.People, People.Name, Sum(([ProjectStatusReport].[Week]), 0, ([ProjectStatusReport].[Week] = #8/27/2004#, 1, 0)) AS Created, Sum((ProjectStatusReport.Week), 0, (ProjectStatusReport.Week = #8/27/2004#, (ProjectStatusReport.Accomplishments) Or (ProjectStatusReport.Plans), 0, 1, 0)) AS Complete, People.email FROM Register INNER JOIN SR_Status ON Register.SR_Status = SR_Status.SR_Status LEFT JOIN ProjectStatusReport ON Register.Register = ProjectStatusReport.Project INNER JOIN StakeHolders ON Register.Register = StakeHolders.Register INNER JOIN People ON StakeHolders.People = People.People WHERE SR_Status.Status='Active' AND StakeHolders.Status = 'Yes' GROUP BY People.People, People.Name, People.email HAVING (Sum(ProjectStatusReport.Week), 0, ((ProjectStatusReport.Week) = #8/27/2004#, 1, 0) > 0)) AND Sum(ProjectStatusReport.Week),0,((ProjectStatusRep ort.Week) = #8/27/2004#,(ProjectStatusReport.Accomplishments) Or (ProjectStatusReport.Plans),0,1,0)>0 ORDER BY People.People