Incorrect syntax error sql - sql-server

CREATE PROC CreateOrUpdate
#ID INT,
#NRIC VARCHAR(50),
#Name VARCHAR(50),
#Description VARCHAR(50),
#Location1 VARCHAR(50)
AS
BEGIN
IF (#ID = 0)
BEGIN
INSERT INTO tblBlacklist (NRIC, Name, Description, createdatetime, Location1)
VALUES (#NRIC, #Name, #Description, GETDATE(), #Location1)
END
ELSE
BEGIN
UPDATE tblBlacklist
SET NRIC = #NRIC,
Name = #Name,
Description = #Description,
createdatetime = GETDATE()
WHERE ID = #ID
AND Location1 = #Location1
END
END
/****** Object: StoredProcedure [dbo].[ContactViewAll] Script Date: 15-
Apr-2017 7:39:13 AM ******/
CREATE PROC ViewAll
#Location1 VARCHAR(50)
AS
BEGIN
SELECT *
FROM tblBlacklist
WHERE Location1 = #Location1
END
I cannot see any errors within my coding. The error message is
Msg 156, Level 15, State 1, Procedure CreateOrUpdate, Line 28 [Batch Start Line 0]
Incorrect syntax near the keyword 'PROC'
Please help me thanks.

One suggestion is to add a go between your two create statements, and remove the system comment:
CREATE PROC CreateOrUpdate
#ID int,
#NRIC varchar(50),
#Name varchar(50),
#Description varchar(50),
#Location1 varchar(50)
AS
BEGIN
IF(#ID=0)
BEGIN
INSERT INTO tblBlacklist(NRIC,Name,Description,createdatetime,Location1)
VALUES(#NRIC,#Name,#Description,getdate(),#Location1)
END
ELSE
BEGIN
UPDATE tblBlacklist
SET
NRIC = #NRIC,
Name = #Name,
Description = #Description,
createdatetime = getdate()
WHERE ID= #ID and Location1=#Location1
END
END
GO
CREATE PROC ViewAll
#Location1 varchar(50)
AS
BEGIN
SELECT *
FROM tblBlacklist
WHERE Location1 = #Location1
END
GO

try surround your input parameters inside fitst brace ()

Related

Incorrect syntax near GOTO label in SQL Server stored procedure

I am using a GOTO statement inside a try block and also in catch block in a stored procedure.When it comes to the definition of GOTO label after END catch, it shows incorrect syntax error. below is the procedure. Error comes at 'AuditLog :' in the procedure. please help me with this.
ALTER PROCEDURE [dbo].[Proc_PIP_Employee]
#Flag int = 1,
#Empid int = 0,
#Name nvarchar(500) = '',
#Designation nvarchar(200) = '',
#Department nvarchar(200) = '',
#DateofJoin datetime = '' ,
#Phone nvarchar(3000) = '',
#Isactive int = 1,
#LoginUser nvarchar(500) = ''
AS
BEGIN
SET NOCOUNT ON ;
DECLARE #r int;
BEGIN TRY
BEGIN TRANSACTION
DECLARE #errorMessage VarChar(8000),
#errorSeverity Int,
#errorState Int,
#ReturnId Int,
#AlCode varchar(50),
#AlDesc varchar(1000),
#AlOp varchar(50),
#AlStatus varchar(50)
IF (#Flag = 1)
BEGIN
IF EXISTS (SELECT 1 FROM dbo.PIP_Employee
GROUP BY Name, Phone
HAVING COUNT(ID) > 0
AND Name = #Name AND Phone = #Phone)
BEGIN
SET #ReturnId = 0
SET #AlCode = 'ERROR_1001'
SET #AlDesc = CONCAT('Add Record of ',#Name,' failed due to duplicate entry')
SET #AlOp = 'ADD'
SET #AlStatus = 'ERROR'
GOTO AuditLog
END
ELSE
BEGIN
INSERT INTO dbo.PIP_Employee (Name, Designation, Department, DateofJoin, Phone, IsPresent)
VALUES (#Name, #Designation, #Department, #DateofJoin, #Phone, #Isactive)
SET #ReturnId = 1
END
END
COMMIT TRANSACTION
END TRY
BEGIN CATCH
SET #AlCode = ERROR_SEVERITY()
SET #AlDesc = ERROR_MESSAGE()
SET #AlOp = 'SQL TRANSACTION FAILURE'
SET #AlStatus = ERROR_STATE();
GOTO AuditLog
IF (##trancount > 0)
ROLLBACK TRANSACTION
END CATCH
AuditLog :
INSERT INTO dbo.PIP_AuditLog (Aud_Code, Aud_Desc, Aud_Operation, Aud_Status, Aud_Createddate, Aud_ActionBy)
VALUES (#AlCode, #AlDesc, #AlOp, #AlStatus, GETDATE(), #LoginUser)
SET NOCOUNT OFF
END
AuditLog : seems to be an incorrect syntax.
If you are not using an IDE with syntax checking like SQL Server Management Studio, you might want to check out some free tools like https://ubitsoft.com/t-sql-beautilyzer/.
This indicates that line 68 is bad. Namely that labels should NOT have a space between the label and the ':'

Retrieve values from database through stored procedure

I have this database with table 'crigsStaffActivity'. I managed to retrieve the values and display it. But the result is not showing as my expectation.
Script to create table with values
CREATE TABLE [dbo].[crigsStaffActivity]
(
[projectRef] [varchar](200) NOT NULL,
[activityLine] [int] NOT NULL,
[cost] [real] NOT NULL,
[staffCost] [varchar](500) NOT NULL
) ON [PRIMARY]
GO
INSERT [dbo].[crigsStaffActivity] ([projectRef], [activityLine], [cost], [staffCost])
VALUES (N'MRC/CRIGS/330', 1, 1, N'ProjectLeader'),
(N'MRC/CRIGS/330', 2, 2, N'Research Collaborators'),
(N'MRC/CRIGS/330', 1, 1, N'Project Collaborators'),
(N'MRC/CRIGS/330', 2, 2, N'Project Collaborators'),
(N'MRC/CRIGS/330', 2, 3, N'Research/Project Assistant');
ALTER TABLE [dbo].[crigsStaffActivity]
ADD CONSTRAINT [DF__crigsStaff__cost__5535A963] DEFAULT ((0)) FOR [cost]
GO
Screenshot of table:
My stored procedure:
ALTER PROCEDURE [dbo].[getCrigsStaffActivity]
#ProjectRef AS VARCHAR(1000),
#staffCost AS varchar(1000)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #val AS VARCHAR(2000);
SET #val='';
DECLARE #temp AS VARCHAR(2000);
DECLARE #activityLine AS VARCHAR(2000);
DECLARE #cost AS VARCHAR(2000);
DECLARE #ref as CURSOR;
SET #ref = CURSOR FOR
SELECT activityLine, cost
FROM crigsStaffActivity
WHERE projectRef = #ProjectRef
AND staffCost = #staffCost
OPEN #ref;
FETCH NEXT FROM #ref INTO #activityLine, #cost;
WHILE ##FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM #ref INTO #activityLine, #cost;
SET #val = CONCAT(#activityLine,',',#cost);
END
CLOSE #ref;
DEALLOCATE #ref;
SELECT #val AS ref;
END
When I execute the stored procedure, I get this result:
ref
----
2,2
The issue is that for project collaborators I have two repeating values, thus I need to get a result like this:
ref
-----
1,1
2,2
My question is how to achieve the result mentioned above.
A better result of this stored procedure could have been:
ref
-----------------------------
1,1,ProjectLeader
2,2,Research collaborators
1,1,Project collaborators
2,2,Project collaborators
2,3,Research/Project Assistant
If I got it correct. you don't need to use the cursor.
ALTER PROCEDURE [dbo].[getCrigsStaffActivity]
#ProjectRef AS VARCHAR(1000),
#staffCost AS varchar(1000)
AS
BEGIN
SET NOCOUNT ON;
SELECT CONCAT(activityLine,',', cost,',', staffCost) as ref
FROM crigsStaffActivity
WHERE projectRef = #ProjectRef
AND staffCost = #staffCost
END
Please try this Procedure.
USE [***]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[getCrigsStaffActivity]
#ProjectRef as VARCHAR(1000),
#staffCost as varchar(1000)
AS
BEGIN
SET NOCOUNT ON;
Declare #val as varchar(2000);
set #val='';
Declare #temp as Varchar(2000);
Declare #activityLine as Varchar(2000);
Declare #cost as Varchar(2000);
DECLARE #ref as CURSOR;
SET #ref = CURSOR FOR
SELECT DISTINCT activityLine, cost
FROM crigsStaffActivity
where projectRef = #ProjectRef
and staffCost = #staffCost
OPEN #ref;
FETCH NEXT FROM #ref INTO #activityLine, #cost;
WHILE ##FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM #ref INTO #activityLine, #cost;
set #val = CONCAT(#activityLine,',',#cost);
END
CLOSE #ref;
DEALLOCATE #ref;
select #val as ref;
END

T-SQL stuck on scope_identity return from stored procedure

I'm sure this is a easy fix, but I can't find an answer here. Been many a years since I have written stored procedures..
These are my procedures:
This first one works, and returns the newly created Id.
ALTER PROCEDURE [dbo].[sp_CreateBytegymType]
#Name NVARCHAR(200),
#Type NCHAR(1),
#Description NVARCHAR(MAX) NULL,
#Comment NVARCHAR(MAX) NULL,
#Source NVARCHAR(MAX) NULL,
#BtId INT OUTPUT
AS
BEGIN
SET NOCOUNT ON
INSERT INTO BytegymType
VALUES (#Name, #Type, #Description, #Comment, #Source)
SET #BtId = CAST(SCOPE_IDENTITY() AS INT)
END
The second one calls the first one:
ALTER PROCEDURE [dbo].[sp_CreateMuscle]
#Name NVARCHAR(200),
#Type NCHAR(1),
#Description NVARCHAR(MAX) NULL,
#Comment NVARCHAR(MAX) NULL,
#Source NVARCHAR(MAX) NULL,
#Group NVARCHAR(20) NULL
AS
BEGIN
DECLARE #BtId int
EXEC sp_CreateBytegymType
#Name = #Name,
#Type = #Type,
#Description = #Description,
#Comment = #Comment,
#Source = #Source,
#BtId = #BtId
INSERT INTO Muscle
VALUES (#BtId, #Group)
END
I get the following error:
Msg 515, Level 16, State 2, Procedure sp_CreateMuscle, Line 20 [Batch Start Line 2]
Cannot insert the value NULL into column 'BtId'
Seems I'm not keeping the #BtId value. Do I need to put it into a new value after executing the sp_CreateBytegymType?
Also I would like to do this in a transactional manner. So if the the insert into Muscle fails, it should rollback the stored procedure insert.
You need to add OUTPUT:
exec sp_CreateBytegymType
#Name = #Name,
#Type = #Type,
#Description = #Description,
#Comment = #Comment,
#Source = #Source,
#BtId = #BtId OUTPUT;
Also prefixing user defined stored procedures with sp_ is not advised. Related article: Is the sp_ prefix still a no-no?

What's wrong with this Registration stored procedure

I'm trying to make a Registration stored procedure and when I execute the code, I get this error. I've googled it but it's more specific message error was not able to find a solution. what can cause issue here? Thanks in advice!
Error:
Msg 156, Level 15, State 1, Procedure SP_Registration, Line 39 [Batch Start Line 9]
Incorrect syntax near the keyword 'SET'.
This is my stored procedure:
-- =============================================
-- Author: <Nika Kalatozi>
-- Create date: <04/07/2017>
-- Description: <Registration Stored Procedure>
-- =============================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SP_Registration]
#Username NVARCHAR(25),
#Password NVARCHAR(30),
#Email NVARCHAR(35),
#Firstname NVARCHAR(25),
#Lastname NVARCHAR(25),
#Gender NVARCHAR(10),
#Birthdate DATE,
#PhoneNumber NVARCHAR(25),
#PersonalID NVARCHAR(11),
#Result VARCHAR(100) OUTPUT
AS
BEGIN
IF EXISTS(SELECT #Username FROM Users WHERE #Username = #Username)
BEGIN
SET #Result = 'The username you have entered is already in use.'
RETURN;
END
ELSE IF EXISTS(SELECT #Email FROM Users WHERE #Email = #Email)
BEGIN
SET #Result = 'The email you have entered is already in use.'
RETURN;
END
ELSE
BEGIN
INSERT INTO Users(Username, [Password], Email, Firstname, Lastname,
Gender, BirthDate, PhoneNumber, PersonalID)
SET #Result = 'You have been registered successfully.'
RETURN;
END
END
In code
INSERT INTO Users(
...
)
you should specify what to insert:
INSERT INTO Users(
...
) VALUES
(#Username, ...) -- specify values in brakets

Instead of insert trigger SQL

I am trying to create an 'instead of insert trigger' that will not let the name 'john' insert anything into a table. My problem is that even if i change the name to something else, the query is successful but the values arent added.
Any help would be appreciated, thanks in advance.
CREATE TRIGGER InsteadOfTrigger
ON Question4
INSTEAD OF INSERT
AS
Declare #name varchar(50)
Declare #question varchar(50)
Declare #Answer char
Set #name = 'John'
IF (select Username from inserted) = #name
BEGIN
RAISERROR ('You have not paid up your fee', 10,1)
ROLLBACK TRANSACTION
END
ELSE
BEGIN
INSERT INTO question4
values (#name, #question, #Answer)
END
Ok So I have removed your BEGIN and END statements between your IF ELSE statement and wrapped the trigger logic within a BEGIN END
As mentioned in the comments below you dont need the ROLLBACK TRANSACTION
Also you will need to populate #question and #Answer for those to be of any use.
CREATE TRIGGER InsteadOfTrigger
ON Question4
INSTEAD OF INSERT
AS
BEGIN
Declare #name varchar(50)
Declare #question varchar(50)
Declare #Answer char
Set #name = 'John'
IF (select Username from inserted) = #name
RAISERROR ('You have not paid up your fee', 10,1)
--ROLLBACK TRANSACTION
ELSE
INSERT INTO question4
values (#name, #question, #Answer)
END
Hmm, I notice you have declared, but not actually set a value for your variables in your else statement this may have caused SQL to not insert what you expected.
Strangely enough I'm required to do the same in an assignment at the moment, Here's my solution:
CREATE TRIGGER instead_of_insert
ON Question4
INSTEAD OF INSERT AS
Declare #Username varchar(25)
Declare #Question varchar(6)
Declare #Answer char(1)
Set #Username ='John'
IF (Select UserName from inserted) = #UserName
Begin
RAISERROR ('You have not paid up your fee', 10,1)
End
Else
Begin
Set #Username = (Select UserName from inserted)
Set #Question = (Select Question_ID from inserted)
Set #Answer = (Select Answer from inserted)
Insert into User_Responses
Values
(#username, #Question, #Answer)
End

Resources