I create trigger
CREATE TRIGGER PartnersTrigger on Partners
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON
Declare @Key nvarchar(10);
EXEC @Key = sp_GeneratePassword 5;
UPDATE Partners SET KeyInvitation = @Key WHERE Id IN (SELECT Id FROM inserted);
INSERT INTO Partners(Email,KeyInvitation)
SELECT Email, KeyInvitation
FROM inserted
END
GO
But I need set to KeyInvitation variable @Key.
And set sp_GeneratePassword 5 (procedure) in @Key.
How to do this?
UPDATE
CREATE PROCEDURE sp_GeneratePassword
(
@Length int
)
AS
DECLARE @RandomID varchar(32)
DECLARE @counter smallint
DECLARE @RandomNumber float
DECLARE @RandomNumberInt tinyint
DECLARE @CurrentCharacter varchar(1)
DECLARE @ValidCharacters varchar(255)
SET @ValidCharacters = 'abcdefghijklmnopqrstuvwxyz0123456789'
DECLARE @ValidCharactersLength int
SET @ValidCharactersLength = len(@ValidCharacters)
SET @CurrentCharacter = ''
SET @RandomNumber = 0
SET @RandomNumberInt = 0
SET @RandomID = ''
SET NOCOUNT ON
SET @counter = 1
WHILE @counter < (@Length + 1)
BEGIN
SET @RandomNumber = Rand()
SET @RandomNumberInt = Convert(tinyint, ((@ValidCharactersLength - 1) * @RandomNumber + 1))
SELECT @CurrentCharacter = SUBSTRING(@ValidCharacters, @RandomNumberInt, 1)
SET @counter = @counter + 1
SET @RandomID = @RandomID + @CurrentCharacter
END
SELECT @RandomID AS 'Password'
GO
this not work:
Declare @Key nvar char(10); -- can't post when I use "nvarchar" here
EXEC @Key = sp_GeneratePassword 5;
Error:
Incorrect syntax near ‘char’. Must declare the scalar variable “@Key”.
Must declare the scalar variable “@Key”. Must declare the scalar
variable “@Key”.
The trigger looks OK apart from the info noted by Michal Powaga and this bit:
Unless
sp_GeneratePasswordhas aRETURNwith a specific value it will usually give 0 because this kind of call assigns the value from theRETURNto@Key. However, this can only be used forintvalues and@Keyis nvarchar.I’d use an output parameter like in this answer from yesterday: Returning a value from a stored procedure
Note; you are assigning all rows in the INSERT the same password (don’t assume triggers operate on single rows). I’d consider a DEFAULT constraint on the
KeyInvitationcolumn that calls a UDF. This avoids a trigger and will give different values (I assume)