Stored procedure help required - sql

I am running this stored procedure and I need it to return a string value of
Success
or
Failed
But the following procedure is missing something, not sure what?
ALTER PROCEDURE [dbo].[sp_Log_Audit]
(
#username varchar(254) = NULL,
#password varchar(254) = NULL,
#User_ID int = NULL,
#Method varchar(10) = NULL,
#Result varchar(10) = Failed
)
AS
SET NOCOUNT ON;
INSERT INTO dbo.[A_Logins]([Username], [Password], [User_ID], [Method], [Result])
VALUES(#userName, #Password, #User_ID, #Method, #Result)
SET NOCOUNT OFF;
RETURN
It should return #Result as it will be having a Success or Failed message

I think you haven't return any value, can you try this at the place of where you wrote return?
SELECT #Result As ReturnVal

Related

Dynamic Name for Database Table - Stored Procedure

I want to create dynamic name for my database tables. I declare variable and use it as my table name.
ERROR: Incorrect syntax near '#sample'. Expecting '.',ID or QUOTED_ID
CREATE PROCEDURE [dbo].[sp_SAMPLE]
#name nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sample nvarchar(50);
SET #sample = 'tbl_function_' + #name;
Create Table #sample
(
id int not null,
UserType nvarchar(50) null,
paramater2 nvarchar(50) null
)
END
Is there any way to make my table name dynamic? Thank you.
I'm not sure why you would want to do this. But, you can do it using dynamic SQL:
CREATE PROCEDURE [dbo].[sp_SAMPLE]
#name nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql nvarchar(max);
SET #sql = '
Create Table tbl_function_#name
(
id int not null,
UserType nvarchar(50) null,
paramater2 nvarchar(50) null
)';
SET #sql = REPLACE(#sql, '#name', #name);
EXEC sp_executesql #sql;
END;
Why would you want to create a separate table for each #name, instead of just inserting rows with #name in a column?
CREATE PROCEDURE [dbo].[sp_SAMPLE]
#name nvarchar(50)
AS
BEGIN
SET NOCOUNT ON
DECLARE #sql varchar(4000);
SET #sql = '
Create Table tbl_function_'+#name+'
(
id int not null,
UserType nvarchar(50) null,
paramater2 nvarchar(50) null
)'
EXEC (#sql)
END

Procedure or function has too many arguments SQL server

I getting this error while executing the stored procedure in SQL Server:
Msg 8144, Level 16, State 2, Procedure sp_adduser, Line 2
Procedure or function sp_adduser has too many arguments specified.
The weird thing is that the number of parameters is the same as declared in the procedure, even when I execute it while right-click on the procedure and press execute, input the parameters from the fields and still the same error.
This is the code of the procedure and the exec:
create procedure [dbo].[sp_addUser]
(
#userID nvarchar(50),
#pw nvarchar(50),
#fName nvarchar(50),
#lname nvarchar(50),
#email nvarchar(150),
#address nvarchar(150),
#city int,
#country int,
#phone nvarchar(50),
#gender nvarchar(10),
#dob date,
#photo nvarchar(150),
#secq int,
#secAnswer nvarchar(150),
#completed int output)
as
declare #found int
/*
usertype:
0 - Administrator
1 - User
*/
begin
begin
select #found=count(*) from registration r
where REPLACE(r.firstname,' ','')=REPLACE(#fName,' ','')
and REPLACE(r.lastname,' ','')=REPLACE(#lname,' ','')
and r.dateofbirth=#dob;
end
begin
if #found=0
begin
begin
insert into Login values(#userID,#pw,0,1);
end
begin
insert into registration values(
#userID,#fName,#lname,#email,
#address,#city,#country,#phone,
#gender,#dob,#photo,#secq,#secAnswer
)
end
begin
set #completed=1;
end
end
else set #completed=0
end
return #completed
end
And here is the exec:
DECLARE #return_value int,
#completed int
SELECT #completed = 0
EXEC #return_value = [dbo].[sp_addUser]
#userID = N'a',
#pw = N'a',
#fName = N'a',
#lname = N'a',
#email = N'a',
#address = N'a',
#city = 1,
#country = 1,
#phone = N'a',
#gender = N'a',
#dob = '01/01/2000',
#photo = N'a',
#secq = 1,
#secAnswer = N'a',
#completed = #completed OUTPUT
SELECT #completed as N'#completed'
SELECT 'Return Value' = #return_value
Thanks in advance!
sp_adduser is a procedure which is built-in to SQL Server - see https://msdn.microsoft.com/en-us/library/ms181422.aspx
Don't use the sp_ prefix for your own stored procedures, maybe call it proc_adduser instead, I think that will work
You are actually calling the system stored procedure sp_adduser. The "sp_" prefix is special and has its own rules on resolution, so using it is recommended against. If you want to use your own prefix, whatever you do, don't use "sp_".
Per #marc_s, even if your stored procedure doesn't clash with an existing system stored procedure, you will still get a noticeable performance hit due to cache misses.

SQL Trigger not firing

I Update the table and the Trigger doesn't fire. Or at least it doesn't seem to insert into the other table the information. Is there something I may be missing in my code?
ALTER TRIGGER [dbo].[UpdateUsers]
ON [VLS_TEST].[dbo].[Identifier]
AFTER UPDATE
AS
DECLARE #Status VARCHAR(4)
DECLARE #License_Nbr VARCHAR(9)
DECLARE #Email VARCHAR (100)
DECLARE #FName VARCHAR(15)
DECLARE #LName VARCHAR(25)
SELECT #Status = Status,
#License_Nbr = License_Nbr,
#Email = Email,
#FName = FName,
#LName = LName
FROM VLS_Test.dbo.Identifier
IF ( #Status = 'LISC'
AND ( #License_Nbr LIKE '__01%'
OR #License_Nbr LIKE '__06%' ) )
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
IF NOT EXISTS (SELECT *
FROM RTT_DEV.dbo.Users
WHERE RTT_DEV.dbo.Users.TerminalOperatorNum = #License_Nbr)
BEGIN
INSERT INTO RTT_DEV.dbo.Users
(Username,
PASSWORD,
UserType,
TerminalOperatorNum,
AdminName,
FirstName,
LastName)
VALUES (#Email,
'********',
'2',
#License_Nbr,
'System',
#FName,
#LName)
END
END

Output last inserted primary key value from stored procedure

I'm having a bit of difficulty with this one in that I'm not sure how to do this in SQL Server.
Basically, I want to insert a new row into the database, get the PK value that was just inserted (same query) and output it back to whatever called the stored procedure:
CREATE PROCEDURE Users_Insert
-- Add the parameters for the stored procedure here
#userid int output,
#name varchar(50),
#surname varchar(50),
#email varchar(200),
#password varchar(50),
#location varchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
insert into Users(FirstName, LastName, Email, Password, Location)
values(#name, #surname, #email, #password, #location);
GO
#userid = ##IDENTITY;
END
I've done this in MySQL as follows:
CREATE PROCEDURE Users_Insert(#userid int output, #name varchar(50), #surname varchar(50), #email varchar(200), #password varchar(50), #location varchar(50)
BEGIN
insert into Users(FirstName, LastName, Email, Password, Location)
values(#name, #surname, #email, #password, #location);
set #userid = last_insert_id();
END
SQL Server gives me an error:
Msg 102, Level 15, State 1, Procedure Users_Insert, Line 18
Incorrect syntax near '#userid'.
Frankly, I'm not sure I declared the output parameter correctly, can anyone offer suggestions?
You need to assign the value to #userid ! Also, I would recommend using SCOPE_IDENTITY() and not ##IDENTITY :
CREATE PROCEDURE Users_Insert
-- Add the parameters for the stored procedure here
#userid int output,
#name varchar(50),
#surname varchar(50),
#email varchar(200),
#password varchar(50),
#location varchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
insert into Users(FirstName, LastName, Email, Password, Location)
values(#name, #surname, #email, #password, #location);
-- make an actual **assignment** here...
SELECT #userid = SCOPE_IDENTITY();
END
See this blog post for an explanation as to WHY you should use SCOPE_IDENTITY over ##IDENTITY

SQL Server: Return uniqueidentifier from stored procedure

Can I return UNIQUEIDENTIFIER from a stored procedure using the RETURN statement or is it only by using the OUTPUT statement?
i.e to return the PersonID UNIQUEIDENTIFIER:
CREATE PROCEDURE CreatePerson
#Name NVARCHAR(255),
#Desc TEXT
AS
DECLARE #Count INT
DECLARE #JobFileGUID UNIQUEIDENTIFIER
-- Check if job exists?
SET #Count = (SELECT COUNT(Name) AS Name FROM Person WHERE Name=#Name)
IF #Count < 1
BEGIN
SET #PersonGUID = NEWID();
INSERT INTO Person
(PersonID, Name, [Desc])
VALUES (#PersonGUID, #Name, #Desc)
END
SELECT #PersonGUID = Person.PersonID
FROM Person
WHERE Name = #Name
RETURN #PersonGUID
GO
Thanks
In stored procedure - only using the OUTPUT statement. In function - return.
Use:
CREATE PROCEDURE CreatePerson
#Name NVARCHAR(255),
#Desc TEXT,
#PersonGUID UNIQUEIDENTIFIER OUTPUT
AS
BEGIN
SET #PersonGUID = ...
END
How to call:
DECLARE
#name NVARCHAR(255),
#desc TEXT,
#personGUID UNIQUEIDENTIFIER
SET #name = 'Bob'
SET #desc = 'One handsome man.'
EXEC [Database].[schema].CreatePerson #name, #desc, #personGUID OUTPUT
From the documentation you can actually see that a return in a stored procedure is actually used as a response code, hence you get the exception when trying to return a uniqueidentifier.
https://learn.microsoft.com/en-us/sql/relational-databases/stored-procedures/return-data-from-a-stored-procedure?view=sql-server-ver16#return-data-using-a-return-code
How I solved it, is by just performing a SELECT after the insert of the generated unique identifier.
DECLARE #ReportId UNIQUEIDENTIFIER;
SET #ReportId = NEWID();
INSERT INTO [dbo].[Report]
([ReportId]
,[ReportName])
VALUES
(#ReportId
,#ReportName)
SELECT #ReportId as ReportIdInternal
You'll have to see how to perform that with multiple selects though.
CREATE TABLE [dbo].[tbl_Clients]( [ClientID] [uniqueidentifier] NULL, [ClientName] varchar NULL, [ClientEnabled] [bit] NULL ) ON [PRIMARY]
GO
CREATE PROCEDURE [dbo].[sp_ClientCreate] #in_ClientName varchar(250) = "New Client 123", #in_ClientEnabled bit, #out_ClientId uniqueidentifier OUTPUT AS
SET #out_ClientId = NEWID();
INSERT INTO tbl_Clients(ClientId, ClientName, ClientEnabled) VALUES( #out_ClientId, #in_ClientName, #in_ClientEnabled)
DECLARE #return_value int, #out_ClientId uniqueidentifier
EXEC #return_value = [dbo].[sp_ClientCreate] #in_ClientName = N'111', #in_ClientEnabled = 1, #out_ClientId = #out_ClientId OUTPUT
SELECT #out_ClientId as N'#out_ClientId'
SELECT 'Return Value' = #return_value
GO
Result:-59A6D7FE-8C9A-4ED3-8FC6-31A989CCC8DB