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
Related
Query returns exactly what I want but when I plug the same structure into my stored Procedure I get a formatting error.
Msg 8116, Level 16, State 1, Procedure RegisterUser, Line 21
Argument data type varchar is invalid for argument 1 of format function.
Here's my query.
DECLARE #Department int
SET #Department = (SELECT DepartmentLink FROM DepartmentMaster WHERE Name =
'Inventory')
DECLARE #Position int
SET #Position = (SELECT TypeLink FROM EmployeeTypes Where Title = 'Clerk')
DECLARE #UID int
set #UID = (SELECT ID FROM EmployeeMaster WHERE FirstName = 'John' and
LastName = 'Doe')
(SELECT convert(varchar,FORMAT (#Department,'00#'))+'-'+
convert(varchar,FORMAT(#Position, '0#'))+'-
'+convert(varchar,FORMAT(#UID,'000#')) as EmployeeID)
Here's my Stored Procedure..
CREATE Procedure RegisterUser
(
#FirstName varchar(255),
#LastName varchar(255),
#Department varchar(255),
#Email varchar(255),
#Password varchar(255),
#UserType varchar(255),
#EmployeeID varchar(255),
#DepartmentLink int,
#Position int,
#UID int
)
AS
SET #Department = (SELECT DepartmentLink FROM DepartmentMaster WHERE Name =
#Department)
SET #Position = (SELECT TypeLink FROM EmployeeTypes Where Title = #UserType)
set #UID = (SELECT ID FROM EmployeeMaster WHERE FirstName = #FirstName and
LastName = #LastName)
SET #EmployeeID = (SELECT convert(varchar,FORMAT (#Department,'00#'))+'-'+
convert(varchar,FORMAT(#Position, '0#'))+'-
'+convert(varchar,FORMAT(#UID,'000#')) as EmployeeID)
INSERT INTO EmployeeMaster(FirstName, LastName, Department,
Email,Password,CreationDate, EmployeeID, Active)
VALUES(#FirstName, #LastName, (SELECT DepartmentLink FROM DepartmentMaster
WHERE Name = #Department), #Email, #Password, GETDATE(),
#EmployeeID
,1)
I would suggest writing this as:
CREATE Procedure RegisterUser (
#FirstName varchar(255),
#LastName varchar(255),
#Department varchar(255),
#Email varchar(255),
#Password varchar(255),
#UserType varchar(255),
#EmployeeID varchar(255),
#DepartmentLink int,
#Position int,
#UID int
) AS
BEGIN
DECLARE #DepartmentLink varchar(255);
DECLARE #PositionLink int;
DECLARE #Uid_new int;
DECLARE #EmployeeId_new varchar(255);
SELECT #DepartmentLink = DepartmentLink
FROM DepartmentMaster
WHERE Name = #Department;
SELECT #PostiionLink = TypeLink
FROM EmployeeTypes
WHERE Title = #UserType;
SELECT #Uid_new = ID
FROM EmployeeMaster
WHERE FirstName = #FirstName and LastName = #LastName;
SELECT #EmployeeID_new = (FORMAT(#Department, '00#') + '-' +
FORMAT(#Position, '0#')) + '-' +
FORMAT(#UID, '000#')
);
INSERT INTO EmployeeMaster(FirstName, LastName, Department, Email, Password, CreationDate, EmployeeID, Active)
VALUES(#FirstName, #LastName,
#DepartmentLink, #Email, #Password, GETDATE(),
#EmployeeID_new, 1
);
END; -- RegisterUser
You could simplify this further.
Notes:
Your code needs a BEGIN/END
Don't assign values to parameters, unless they are output parameters. Instead, use local variables.
FORMAT() already returning a string -- no need for another conversion.
SET with a subquery just looks awkward to me, when you can do the assignment with a SELECT.
I don't think you need all the arguments, but that is another matter.
IdentityId is of UNIQUEIDENTIFIER type and when I insert a record and set that as NewId(), I get the error message
Incorrect Syntax new )
Not sure what I am missing. Please advice.
Execute command:
Exec dbo.CreateUser
#Title = 'MR',
#FirstName = 'John',
#LastName = 'Smith',
#IdentityId = NewId(),
#PhoneNumber = '01234456789',
#MobileNumber = '0987654321',
#StatesId = 2,
#AddressLineOne = '1 A Road',
#AddressLineTwo = '',
#Town = 'Some Town',
#County = 'County',
#PostCode = 'AA1 1AA',
#Country = 'United Kingdom',
#OrganisationName = 'OrgName',
#OrganisationDomain = 'orgName.com'
CreateUser stored procedure:
CREATE PROCEDURE [dbo].[CreateUser]
#Title NVARCHAR(50),
#FirstName NVARCHAR(50),
#LastName NVARCHAR(50),
#IdentityId UNIQUEIDENTIFIER,
#PhoneNumber NVARCHAR(50),
#MobileNumber NVARCHAR(50),
#StatesId INT,
#AddressLineOne NVARCHAR(MAX),
#AddressLineTwo NVARCHAR(MAX),
#Town NVARCHAR(50),
#County NVARCHAR(50),
#PostCode NVARCHAR(10),
#Country NVARCHAR(20),
#OrganisationName NVARCHAR(MAX),
#OrganisationDomain NVARCHAR(MAX)
AS
INSERT INTO Addresses (AddressLineOne, AddressLineTwo, Town, County, PostCode, Country)
VALUES (#AddressLineOne, #AddressLineTwo, #Town, #County, #PostCode, #Country)
INSERT INTO Organisations(Name, Domain, AddressId)
VALUES (#OrganisationName, #OrganisationDomain, SCOPE_IDENTITY())
INSERT INTO Users (Title, FirstName, LastName, IdentityId, MobileNumber, PhoneNumber, OrganisationId, StatesId, DateCreated)
VALUES (#Title, #FirstName, #LastName, #IdentityId, #PhoneNumber, #MobileNumber, SCOPE_IDENTITY(), #StatesId, GETDATE())
Set the value to a variable and use that:
declare #id uniqueidentifer;
set #id = newid();
exec . . .
#IdentityId = #id,
. . .;
There is nothing specific about newid() here. The exec statement doesn't parse expressions, even simple function calls.
Also, but begin and end around the stored procedure body. You should always do this, to prevent unexpected errors.
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
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
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