Ms Sql Trigger Permission - sql-server

This trigger was not written by me or used with a stored proc original I modified it for my use. The problem to me appears to be one of permissions when the table is manually updated or inserted inSQL Server Management Studio the trigger works perfectly. When the Trigger is updated or inserted by a Stored Proc ran via an ODBC connection it does not modify the table and the Trigger does not work. If the trigger is disabled the stored Proc works as expected. So the error appers to be some form of permission error. Here is the trigger. (Using 2012)
Thanks In Advance
Donald S. Bossen
USE [JBI]
GO
/****** Object: Trigger [dbo].[send_ship_exec_info_to_p21] Script Date: 8/29/2018 3:22:26 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[send_ship_exec_info_to_p21] ON [dbo].[ship_exec]
FOR INSERT, UPDATE
AS
declare #pick_ticket_no varchar(50)
declare #tracking_no varchar(50)
declare #pickup_date varchar(50)
declare #carrier_id varchar(50)
declare #package_count varchar(50)
declare #delete_flag varchar(50)
declare #package_weight varchar(50)
declare #package_charge decimal(9,4)
declare #total_shipment_charge decimal(19,4)
declare #carrier_name varchar(50)
declare #customer_freight_charge decimal(9,4)
declare #saturday_delivery varchar(50)
declare #transaction_type varchar(50)
declare #billing_option varchar(3)
select
#pick_ticket_no = i.pick_ticket_no,
#tracking_no = i.tracking_no,
#pickup_date = i.pickup_date,--left(i.pickup_date,8),
#carrier_id = i.service_type,
#package_count = i.package_count,
#delete_flag = i.delete_flag,
#package_weight = i.package_weight,
#package_charge = i.package_charge,
#total_shipment_charge = i.total_shipping_and_handling_charge,
#saturday_delivery = i.saturday_delivery,
#transaction_type = i.transaction_type,
#billing_option = i.billing_option
from inserted i
if #transaction_type = 'Inv Return'
begin
declare #document_link_uid int
declare #document_link_area_uid int
declare #link_name varchar(255)
declare #link_path varchar(4099)
set #link_name = 'UPS shipment ' + cast(#pick_ticket_no as varchar(40)) + ': ' + #tracking_no
set #link_path = 'http://wwwapps.ups.com/WebTracking/processInputRequest?HTMLVersion=5.0&sort_by=status&term_warn=yes&tracknums_displayed=5&TypeOfInquiryNumber=T&loc=en_US&InquiryNumber1=' + #tracking_no + '&InquiryNumber2=&InquiryNumber3=&InquiryNumber4=&InquiryNumber5=&AgreeToTermsAndConditions=yes&track.x=28&track.y=2'
if #delete_flag = 'Y'
begin
update
PROPHET21.dbo.document_link
set
row_status_flag = '700'
,date_last_modified = getdate()
,last_maintained_by = 'Ship Exec Delete Flag'
where
key1_cd = 'return_number'
and key1_value = #pick_ticket_no
and link_path like '%' + #tracking_no + '%'
end
if #delete_flag = 'N'
begin
if not exists(select document_link_uid from PROPHET21.dbo.document_link where link_path like '%' + #tracking_no + '%')
begin
exec #document_link_uid = PROPHET21.dbo.p21_get_counter 'document_link', 1
INSERT INTO
PROPHET21.dbo.document_link
(
document_link_uid
,source_area_cd
,key1_cd
,key1_value
,link_name
,link_path
,row_status_flag
,date_created
,created_by
,date_last_modified
,last_maintained_by
,outside_use_flag
,mandatory_flag
)
VALUES
(
#document_link_uid
,1312
,'return_number'
,#pick_ticket_no
,#link_name
,#link_path
,704
,getdate()
,'SHIP EXEC'
,getdate()
,'SHIP EXEC'
,'N'
,'N'
)
exec #document_link_area_uid = PROPHET21.dbo.p21_get_counter 'document_link_area', 1
INSERT INTO
PROPHET21.dbo.document_link_area
(
document_link_area_uid
,document_link_uid
,display_area_cd
,row_status_flag
,date_created
,created_by
,date_last_modified
,last_maintained_by
)
VALUES
(
#document_link_area_uid
,#document_link_uid
,1312
,704
,getdate()
,'SHIP EXEC'
,getdate()
,'SHIP EXEC'
)
end
end
end
if #transaction_type <> 'SWS' or not exists(select oe_pick_ticket.pick_ticket_no from PROPHET21.dbo.oe_pick_ticket oe_pick_ticket where oe_pick_ticket.pick_ticket_no = #pick_ticket_no)
return
if #transaction_type = 'SWS' and exists(select oe_pick_ticket.pick_ticket_no from PROPHET21.dbo.oe_pick_ticket oe_pick_ticket where oe_pick_ticket.pick_ticket_no = #pick_ticket_no)
begin
if (#delete_flag = 'Y')
begin
declare #invoiced_already varchar (50)
select #invoiced_already = oe_pick_ticket.invoice_no
from PROPHET21.dbo.oe_pick_ticket oe_pick_ticket
where pick_ticket_no = #pick_ticket_no
if(#invoiced_already is null)
begin
update PROPHET21.dbo.clippership_return_10004
set delete_flag = 'Y'
where tracking_no = #tracking_no
update PROPHET21.dbo.oe_pick_ticket
set freight_out = 0, date_last_modified = getdate(), last_maintained_by = 'Ship Exec void package'
where pick_ticket_no = #pick_ticket_no
end
return
end
if (#delete_flag = 'N')--#tracking_no like '1z%' and
Begin
declare #customer_pays_outgoing_freight char(1)
select
#customer_pays_outgoing_freight = freight_code.outgoing_freight
from
PROPHET21.dbo.oe_pick_ticket oe_pick_ticket
inner join PROPHET21.dbo.freight_code freight_code on oe_pick_ticket.freight_code_uid = freight_code.freight_code_uid and oe_pick_ticket.company_id = freight_code.company_id
where
oe_pick_ticket.pick_ticket_no = #pick_ticket_no
select
#carrier_name = carrier.name
from
PROPHET21.dbo.address carrier
where
carrier.id = #carrier_id
select #customer_freight_charge =
cast(case
when #billing_option in ('REC', 'TP', 'CB') then 0
when coalesce(#customer_pays_outgoing_freight, 'Y') = 'N' then 0
else ((#total_shipment_charge) / #package_count)
end as decimal(19,2))
update PROPHET21.dbo.oe_pick_ticket
set freight_out = isnull(freight_out, 0) + isnull(#customer_freight_charge, 0),
carrier_id = #carrier_id,
tracking_no = #tracking_no
where pick_ticket_no = #pick_ticket_no
insert into PROPHET21.dbo.clippership_return_10004
(pick_ticket_no,
tracking_no,
package_weight,
order_count,
shipped_date,
carrier_name,
total_charge,
processed_flag,
delete_flag,
date_created,
date_last_modified,
last_maintained_by,
line_number)
values
(#pick_ticket_no,
#tracking_no,
#package_weight,
#package_count,
#pickup_date,
#carrier_name,
#customer_freight_charge,
'N',
'N',
getdate(),
getdate(),
'SHIP EXEC',
0)
end
return
End

Related

SQL SERVER 2016 -CAN execute SP with parameters inside a Function?

I have an SP which brings a table with some fields and subtracts the results to another table, I tried to do this as a function but as you know you can not use DML sentences in a function so I created this SP:
CREATE OR ALTER PROCEDURE SP_Integraciones_AsignarLotesLineas
#Cantidad numeric, #producto nvarchar(max), #bodega nvarchar(max)
AS
BEGIN
BEGIN TRY
BEGIN TRAN
DECLARE #temp as table(idLoteT nvarchar(max), CantidadT numeric, FechaT date)
DECLARE #loteAc nvarchar(Max), #CantidadAc numeric, #restante numeric , #Cont numeric, #fechaAc date, #resultado nvarchar(max)
SET #Cont = #Cantidad
DECLARE CursoIns CURSOR SCROLL
FOR SELECT IdLote, CONVERT(NUMERIC,cantidad), Fecha
FROM tblintegraciones_lotes
WHERE idproducto = #producto
AND Bodega = #bodega
AND cantidad > '0.0'
ORDER BY fecha ASC
OPEN CursoIns
FETCH CursoIns INTO #loteAc, #CantidadAc, #fechaAc
WHILE( #Cont > 0 AND ##FETCH_STATUS = 0 )
BEGIN
IF( #CantidadAc >= #Cont )
BEGIN
SET #restante = #CantidadAc- #Cont
INSERT INTO #temp(
idLoteT, CantidadT, FechaT
)VALUES(
#loteAc, #Cont, #fechaAc
)
UPDATE tblintegraciones_lotes SET Cantidad = #restante WHERE idProducto = #producto AND IdLote = #loteAc
SET #Cont = #cont - #CantidadAc
END
ELSE
BEGIN
SET #Cont = #Cont - #CantidadAc
SET #restante = #Cont - #CantidadAc
INSERT INTO #temp(
idLoteT, CantidadT, FechaT
)VALUES(
#loteAc, #CantidadAc, #fechaAc
)
UPDATE tblintegraciones_lotes SET Cantidad = 0 WHERE idProducto = #producto AND IdLote = #loteAc
END
FETCH CursoIns INTO #loteAc, #CantidadAc, #fechaAc
END
CLOSE CursoIns;
DEALLOCATE CursoIns;
SELECT * FROM #temp
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK
DECLARE #DescripcionError AS nvarchar(max)
SET #DescripcionError = ERROR_MESSAGE()
RAISERROR (#DescripcionError, 18, 1, 'Inventario - lotes - Integraciones', 5)
END CATCH
END
GO
but the problem is that I must run this in a select since I need that query parcing to JSON, so there should be 2 solutions:
Execute this SP in a select sentence
Create some function that calls the SP.
Can you help me how can I execute this SP in a function or find the best soluction?
Here the Query that I need execute this:
(SELECT CASE
WHEN MFAC.codigo IN ('ME-14009',
'ME-14010',
'ME-14011') THEN 'IMP-BOLSAP'
ELSE MFAC.codigo
END AS ItemCode,
REPLACE(MFAC.cantidad, ',', '.') AS Quantity,
CASE WHEN MFAC.codigo LIKE '%PV%' THEN MFAC.valor ELSE null END as Price,
REPLACE(MFAC.descuento, ',', '.') AS DiscountPercent,
CASE
WHEN MFAC.codbodega = 'PV-PER' THEN 'PV-DQU'
ELSE MFAC.codbodega
END AS WarehouseCode,
#OcrCode3 AS CostingCode3,
#OcrCode3 AS COGSCostingCode3
FOR JSON PATH
) DocumentLines

Update statement in stored procedure with varbinary parameter

I have the following table:
CREATE TABLE NZQA_Unit(
NZQAUnitID int IDENTITY(1,1) PRIMARY KEY NOT NULL,
NZQAUnitNumber int NOT NULL,
Title nvarchar(255) NOT NULL,
Level smallint NOT NULL,
Credits smallint NOT NULL,
Classification nvarchar(255) NULL,
AvailableGrade int NULL DEFAULT 1,
Purpose nvarchar(max) NULL,
Validity int NOT NULL DEFAULT 1, -- by default the unit will be 'Current'
Document VARBINARY(MAX) NULL, -- for being able to upload a PDF or Word document
DocumentExtension varchar(5) NULL, -- for storing the file extension
CONSTRAINT AK_NZQA_Unit_Title UNIQUE(Title),
CONSTRAINT AK_NZQA_Unit_Number UNIQUE(NZQAUnitNumber),
CONSTRAINT FK_NZQA_Unit_Validity FOREIGN KEY (Validity) REFERENCES NZQA_Unit_Validity (ValidityID),
CONSTRAINT FK_NZQA_Unit_AvailableGrade FOREIGN KEY (AvailableGrade) REFERENCES NZQA_Unit_Assessment_Grade (AssessmentGradeID),
CONSTRAINT CK_NZQA_Unit_Title CHECK ((len(ltrim(rtrim(Title)))>(2))),
CONSTRAINT CK_NZQA_Unit_ID_Range CHECK (NZQAUnitNumber >= 1000 AND NZQAUnitNumber <= 99999), --Inclusive
CONSTRAINT CK_NZQA_Unit_Level CHECK (Level >= 1 AND Level <= 10), -- Level must be between 1 and 10 https://www.nzqa.govt.nz/studying-in-new-zealand/understand-nz-quals/
CONSTRAINT CK_NZQA_Unit_Credits CHECK (Credits >= 1 AND Credits <= 999), -- 999 has been set arbitrarily but it's high enough to fit an Engineering Degree
CONSTRAINT CK_NZQA_Unit_DocumentSize CHECK (DATALENGTH(Document) <= 524288), -- Maximum size 500 KB https://stackoverflow.com/questions/34741079/can-i-set-2-mb-for-maximum-size-of-varbinary https://www.gbmb.org/mb-to-bytes
CONSTRAINT CK_NZQA_Unit_DocumentExtension CHECK (DocumentExtension IN ('.pdf', '.doc', '.docx')) -- this check is not case sensitive, i.e. '.DOCX' won't trigger an error
);
GO
And I'm writing the following stored procedure:
DROP PROCEDURE IF EXISTS Modify_NZQA_Unit
GO
CREATE PROCEDURE Modify_NZQA_Unit
#NZQAUnitID int,
#NZQAUnitNumber int,
#Title nvarchar(255),
#Level smallint,
#Credits smallint,
#Classification nvarchar(255) NULL,
#AvailableGrade int,
#Purpose nvarchar(max),
#Validity int,
#Document VARBINARY(MAX),
#DocumentExtension varchar(5),
#overwriteFile bit -- 1 to overwrite, 0 to no overwrite
AS
BEGIN
IF (#NZQAUnitID IS NULL)
BEGIN
THROW 51006, 'You must input the NZQA identifier (NZQAUnitID)', 1;
END
SET #Title = Replace(#Title, '''', '''''') -- singles quotes must be escaped
SET #Classification = Replace(#Classification, '''', '''''')
SET #Purpose = Replace(#Purpose, '''', '''''')
SET #DocumentExtension = Replace(#DocumentExtension, '''', '''''')
DECLARE #updateStatement AS NVARCHAR(1000);
SET #updateStatement = 'UPDATE NZQA_Unit SET NZQAUnitNumber = '+CONVERT(VARCHAR, #NZQAUnitNumber)+', Title = '''+#Title+''', Level = '+CONVERT(VARCHAR, #Level)+', Credits = '+CONVERT(VARCHAR, #Credits)+', Classification = '''+#Classification+''', AvailableGrade = '+CONVERT(VARCHAR, #AvailableGrade)+', Purpose = '''+#Purpose+''', Validity = '+CONVERT(VARCHAR, #Validity)
IF (#overwriteFile IS NULL)
BEGIN
THROW 51007, 'Variable #overwriteFile cannot be null', 1;
END
ELSE
BEGIN
IF (#overwriteFile = 1)
BEGIN
IF (#Document IS NULL)
BEGIN
THROW 51008, 'If the variable #overwriteFile is set to 1, a file (#Document) must be provided', 1;
END
IF (#DocumentExtension IS NULL)
BEGIN
THROW 51009, 'If the variable #overwriteFile is set to 1, the document extension (#DocumentExtension) must be provided', 1;
END
SET #updateStatement = #updateStatement + ', Document = '+'HERE WILL COME THE VARBINARY'+', DocumentExtension = '''+#DocumentExtension + ''' '
--DOESN'T WORK: EXEC('UPDATE NZQA_Unit SET NZQAUnitNumber = '+#NZQAUnitNumber+', Title = '''+#Title+''', Level = '+#Level+', Credits = '+#Credits+', Classification = '''+#Classification+''', AvailableGrade = '+#AvailableGrade+', Purpose = '''+#Purpose+''', Validity = '+#Validity + ', Document = ' + #document + ', DocumentExtension = '''+#DocumentExtension + ''' ' +' WHERE NZQAUnitID = '+#NZQAUnitID)
UPDATE NZQA_Unit SET NZQAUnitNumber = #NZQAUnitNumber, Title = #Title, Level = #Level, Credits = #Credits, Classification = #Classification, AvailableGrade = #AvailableGrade, Purpose = #Purpose, Validity = #Validity, Document = #document, DocumentExtension = #DocumentExtension WHERE NZQAUnitID = #NZQAUnitID
END
ELSE
BEGIN
UPDATE NZQA_Unit SET NZQAUnitNumber = #NZQAUnitNumber, Title = #Title, Level = #Level, Credits = #Credits, Classification = #Classification, AvailableGrade = #AvailableGrade, Purpose = #Purpose, Validity = #Validity WHERE NZQAUnitID = #NZQAUnitID
END
END
SET #updateStatement = #updateStatement +' WHERE NZQAUnitID = '+CONVERT(VARCHAR, #NZQAUnitID)
PRINT #updateStatement
END
GO
How could I insert the varbinary data (#Document) into the #updateStatement variable? That way I could simply do a EXEC(#updateStatement)?
Code to execute the procedure below:
DECLARE #current AS INT = 1
DECLARE #expiring AS INT = 2
DECLARE #expired AS INT = 3
DECLARE #achieved AS INT = 1
DECLARE #datos AS VARBINARY(30) = CONVERT(varbinary(30), N'this IS a test')
INSERT NZQA_Unit (NZQAUnitNumber, [Title], [Level], [Credits], [Classification], [AvailableGrade], [Purpose], Validity) VALUES (6401, N'Provide first aid', 2, 1, N'Health Studies > First Aid', #achieved, N'People credited with this unit standard are able to provide first aid.', #current)
EXEC Modify_NZQA_Unit 1, 6424, N'Provide first aid', 2, 1, N'Health Studies > First Aid', #achieved, N'People credited with this unit standard are able to provide first aid.', #current, #datos, '.pdf', 1

MicrosoftSQL: How to create a table inside a Trigger and insert values

im trying to create a trigger on a table with the follow characteristics
Whenever and UPDATE is used on Project_Ypalliloi (table name) i would like to Create another Table (for instance deleted_Ypalliloi)
I would like to take the deleted line, and insert it into the new Table
this is my table:
create table Project_Ypalliloi
(
arithmos_taut int primary key not null,
onoma varchar(20)not null,
eponymo varchar(20)not null,
imerominia_proslipsis date not null,
imerominia_gennisis date not null,
misthos float
)
this is my trigger:
CREATE TRIGGER deleteTrigger ON Project_Ypalliloi FOR DELETE AS --errorline1
DECLARE #arithmos_taut int
DECLARE #onoma varchar(20)
DECLARE #eponymo varchar(20)
DECLARE #imerominia_proslipsis date
DECLARE #imerominia_gennisis date
DECLARE #misthos float
DECLARE #getnamesCursor CURSOR
SET #getnamesCursor = CURSOR FOR
SELECT arithmos_taut,onoma,eponymo,imerominia_proslipsis,imerominia_gennisis,misthos FROM Project_Ypalliloi --where How can i get the deleted line?(under what condition?)
OPEN #getnamesCursor
FETCH NEXT FROM #getnamesCursor INTO #arithmos_taut,#onoma,#eponymo,#imerominia_proslipsis,#imerominia_gennisis,#misthos
WHILE ##FETCH_STATUS = 0
BEGIN
INSERT INTO deleted_Ypalliloi Values '('+rtrim(#arithmos_taut) + ',' + rtrim(#onoma) + ',' + rtrim(#eponymo) + ' ,' + rtrim(#imerominia_proslipsis) + ',' + rtrim(#imerominia_gennisis) + ', ' + rtrim(#misthos)+')'
--FETCH NEXT FROM #getnamesCursor INTO #c_name,#c_surname
END --errorline 2
CLOSE #getnamesCursor
DEALLOCATE #getnamesCursor
My trigger code is in the Query,and i get an error:"Incorrect Syndax at errorline 1 and errorline 2
Thanks a lot for your help
USE "FROM DELETED"
CREATE TRIGGER deleteTrigger ON Project_Ypalliloi AFTER DELETE
AS
BEGIN
DECLARE #arithmos_taut int;
DECLARE #onoma varchar(20);
DECLARE #eponymo varchar(20);
DECLARE #imerominia_proslipsis date;
DECLARE #imerominia_gennisis date;
DECLARE #misthos float;
SELECT #arithmos_taut = arithmos_taut,
#onoma = onoma, #eponymo = eponymo,
#imerominia_proslipsis = imerominia_proslipsis,
#imerominia_gennisis = imerominia_gennisis,
#misthos = misthos FROM DELETED;
INSERT INTO deleted_Ypalliloi
VALUES(#arithmos_taut, #onoma, #eponymo, #imerominia_proslipsis, #imerominia_gennisis, #misthos);
END
For two or more deleted rows
INSERT INTO deleted_Ypalliloi SELECT * FROM DELETED;

Foreach update with parameter separated with a delimiter in SQL Server stored procedure

UPDATE SampleTable
SET Schemaname = #SchemaName,
SchemaCode = #SchemaCode,
ForeignKeyColumn = #ForeignKeyColumn,
IsChildSchema = #IsChildSchema,
ModifiedBy = #ModifiedBy,
ModifiedDate = #ModifiedDate
WHERE
DataSchemaID = #DataSchemaId
My #ForeignKeyColumn parameter is
2233^SITE_CLM_NUMBER,2236^SITE_ID_N,
Can anyone help me in updating ForeignKeyColumn='SITE_CLM_NUMBER' where DataSchemaID=2233 and ForeignKeyColumn='SITE_ID_N' where DataSchemaID=2236
It's easy to pass multiple parameter values to a query, using a Table Valued Parameter. These are available in all versions of SQL Server since 2008.
First, you need to create a Table type with the fields you want:
CREATE TYPE dbo.KeyValueType AS TABLE
( Key int, Value nvarchar(50) )
This allows you to specify a parameter of type KeyValueType with the Key/Value combinations you want, eg #updatedColumns.
You can join the target table with the TVP to update rows with matching DataSchemaID values:
Create Procedure UpdateSchemas(...., #updatedColumns dbo.KeyValueType)
UPDATE SampleTable
SET
Schemaname=#SchemaName
,SchemaCode=#SchemaCode
,ForeignKeyColumn=t.Value
,IsChildSchema=#IsChildSchema
,ModifiedBy=#ModifiedBy
,ModifiedDate=#ModifiedDate
FROM SampleTable
INNER JOIN #updatedColumns t
ON t.ID=DataSchemaID
You can add an SplitString function, like this one :
How to Split String by Character into Separate Columns in SQL Server
CREATE FUNCTION [dbo].[Split]
(
#String varchar(max)
,#Delimiter char
)
RETURNS #Results table
(
Ordinal int
,StringValue varchar(max)
)
as
begin
set #String = isnull(#String,'')
set #Delimiter = isnull(#Delimiter,'')
declare
#TempString varchar(max) = #String
,#Ordinal int = 0
,#CharIndex int = 0
set #CharIndex = charindex(#Delimiter, #TempString)
while #CharIndex != 0 begin
set #Ordinal += 1
insert #Results values
(
#Ordinal
,substring(#TempString, 0, #CharIndex)
)
set #TempString = substring(#TempString, #CharIndex + 1, len(#TempString) - #CharIndex)
set #CharIndex = charindex(#Delimiter, #TempString)
end
if #TempString != '' begin
set #Ordinal += 1
insert #Results values
(
#Ordinal
,#TempString
)
end
return
end
Now you can easily extract each part of your input parameter.
declare #I int;
declare #TMP nvarchar(255);
set #I = 1;
set #TMP = null;
set #TMP = (select StringValue from Split(#ForeignKeyCoumn, ',') where Ordinal = 1);
while #TMP <> null
begin
set #ForeignKeyColumn = (select StringValue from Split(#TMP, '^') where Ordinal = 1);
set #DataSchemaID = (select StringValue from Split(#TMP, '^') where Ordinal = 2);
-- Update here your table with #ForeignKeyColumn and #DataSchemaID values
set #I = #I + 1;
set #TMP = null;
set #TMP = (select StringValue from Split(#ForeignKeyCoumn, ',') where Ordinal = #I);
end
PS: If your are using SQL Server 2016 it already includes an SplitString function, so you won't need to add your own. https://learn.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql

t sql call function as while parameter

is it possible in T SQL to use a function as a while parameter? I have the following code:
create function LoginExists (#p_login char(6))
returns varchar(5)
begin
if exists(select * from Student where student.slogin = #p_login)
return 'true'
return 'false'
end;
and
create procedure AddStudent2
(#p_fname varchar(30), #p_lname varchar(50), #p_tallness int)
as
declare #p_login char(6), #p_email varchar(50), #suffix char(3);
set #p_lname = LOWER(#p_lname);
set #suffix = '000';
begin
set #p_login = substring(#p_lname,1, 3) + #suffix;
while (LoginExists #p_login = 'true')
set #suffix = cast((CAST(#suffix as int) + 1) as char(3));
set #p_login = substring(#p_lname,1, 3) + #suffix;
set #p_email = #p_login + '#vsb.cz';
insert into Student values (#p_login, #p_fname, #p_lname, #p_email, #p_tallness);
end;
and when trying to compile it, an error occurs, saying: "Incorrect syntax near '#p_login'."
Your syntax for calling a function is in fact incorrect:
Replace:
while (LoginExists #p_login = 'true')
with:
while (dbo.LoginExists (#p_login)= 'true')
Replace
if exists(select * from Student where student.slogin = #p_login)
by
if exists(select * from Student where Student.slogin = #p_login)
Upper 'S' in student.slogin and i hope it work

Resources