I am having an issue dropping this function. I am declaring this function within the sp:
Error: There is already an object named 'extract' in the database.
IF OBJECT_ID('[rpt].[MissMatchesReport]') IS NOT NULL
BEGIN
DROP PROCEDURE [rpt].[MissMatchesReport]
END
GO
CREATE procedure [rpt].[MissMatchesReport]
as
IF object_id(N'extract', N'FN') IS NOT NULL
DROP FUNCTION extract
GO
create function [rpt].extract (@fileName varchar(1236))
returns varchar(123)
as
begin
declare @fileINS as integer = 1, @j int
while 1 = 1
begin
SET @j = charindex('\', @fileName, @fileINS)
if @j < 1
break
SET @fileINS = @j + 1
end
return substring(@fileName, @fileINS, LEN(@filename) - @fileins+1)
end
GO
The only reason I am using this function to make changes into a temp table I created. May be I should drop the function at the end of the sp? However, this SP is for a report so I am not sure if I drop the SP at the end of the execution would still keep everything working in SSRS.
I am very new to SSRS and SQL. Any help is appreciated!
Thanks!
Where to start. T-SQL is not like other programming languages. You cannot nest the definitions of stored procedures and functions. This is a limitation, but you do get used to it pretty quickly. The documentation is pretty clear on this point (see the Limitations and Restrictions).
You may think you are declaring the function inside the SP, but you are not. In fact, the SP you have is, in its entirety, the following:
CREATE procedure [rpt].[MissMatchesReport]
as
IF object_id(N'extract', N'FN') IS NOT NULL
DROP FUNCTION extract
GO
The GO
ends the batch unit where the SP is defined. So that is the definition. (You are allowed to drop a function in an SP.) The definition of the function is outside the scope of the SP.
As a matter of practice, it is a good idea to put the body of an SP in a begin
/end
block. It is even better practice (but more advanced) to put it in a begin try/
end catch` block, so you can trap many errors that occur -- if you want to handle them in the SP.
You need to rewrite your code with the idea that you can't nest functions and stored procedures. You should probably keep the function around. Perhaps give it a complicated name, like ufn_MissMatchesReport_extract
.