break and return #temp_catid if(true) - sql

i have a following sql function which takes a string word as input it then checks whether the word is equal to a categoryName or not i want it to behave like when the if statement is true it breaks from the loop and return #temp_catid else it returns 0 or 1 how can i do that im new to sql scripting plz help... below is my function
USE [myDB]
GO
/****** Object: UserDefinedFunction [dbo].[udfisEqualToCategory] Script Date: 01/31/2011 10:57:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create FUNCTION [dbo].[udfisEqualToCategory](#word nvarchar(max))
RETURNS INT
AS
BEGIN
--declare a temp category table for data processing
declare #temptbl_category Table
(
indexx int identity(1,1),
categoryid int,
categoryname nvarchar(max)
)
--insert data from feedcrawler.category into temp category table
insert into #temptbl_category
select CategoryId,Name
from Category
--declare some variables to hold the data of current row of temp category table being processed while looping
declare #temp_catid int
declare #temp_catname nvarchar(max)
declare #rowcount int
set #rowcount=(select count(indexx)from #temptbl_category)
declare #I int
set #I=1
--print'given string-> '+ #FullName
--print'string length-> '+convert(nvarchar(max),#strlen)
while(#I <= #rowcount)
begin
select #temp_catname=categoryname,#temp_catid=categoryid from #temptbl_category where indexx=#I
set #temp_catname=lower(#temp_catname)
if(#word=#temp_catname)
begin
return #temp_catid
break
end--end if
set #I=#I+1
END--while loop ends
return 0
end-- function ends
GO

No need to loop, just search the table with WHERE
Create FUNCTION [dbo].[udfisEqualToCategory](#word nvarchar(max))
RETURNS INT
AS
BEGIN
declare #temp_catid int
select
#temp_catid = categoryid
from
Category
WHERE
LOWER(#word) = LOWER(categoryname);
--no match = #temp_catid IS NULL. So change to zero
RETURN ISNULL(#temp_catid, 0);
END
GO

Related

How can I return tables with different number of parameters with procedure?

I'm going to create different temp tables depending on the #selection parameter I get, and then I want to return the table I created.
I actually wanted to do it with the function, but I got an error for variable parameter tables. The sql procedur I wrote is as follows:
ALTER PROCEDURE [dbo].[Report]
(#Id BIGINT = 55,
#selection INT)
AS
BEGIN
IF #selection=1
BEGIN
Declare #tep_table table (Id int
,Name varchar(250)
,CreateTime datetime
,UpdateTime datetime
,UpdatedBy varchar(250)
,Deleted bit
)
Insert into #tep_table
Select * from User
END
IF #selection=1
BEGIN
Declare #tep_table2 table (Id int
,CreateTime datetime
,UpdateTime datetime
,UpdatedBy varchar(250)
,Deleted bit
)
Insert into #tep_table2
Select * from Client
END
IF #selection=1
BEGIN
RETURN #tep_table
END
ELSE
BEGIN
RETURN #tep_table2
END
END
I am getting this error:
Must declare the scalar variable "#tep_table"
Personally I would turn this into three procedures to avoid the performance problems faced with multiple execution paths.
Something like this.
ALTER Procedure [dbo].[Report]
(
#Id bigint = 55 --not sure what the point of this parameter is as it wasn't used anywhere in the sample code
, #selection int
) AS
set nocount on;
IF #selection = 1
exec GetUserData;
IF #selection = 2
exec GetClientData;
GO
create procedure GetUserData
AS
set nocount on;
Select * --would prefer to use column names here instead of *
from [User];
GO
create procedure GetClientData
AS
set nocount on;
Select * --would prefer to use column names here instead of *
from Client;
GO

A Split Function to Extract the String 'go'

I have a table-valued function called Split. The function takes 2 strings. It will split the 1st string into rows based on the value of the 2nd string.
I want to the function to split sql on the 'go' statements. The problem is that it will split the sql string when it finds the string 'go' anywhere in the sql. I need it to split on the string 'go' only when it is on a line all by itself. Any ideas? I am hoping not to have to re-write the function but to modify it in some (hopefully simple) way.
IF EXISTS (SELECT * FROM sys.objects WHERE
type = 'TF' AND name = 'Split')
BEGIN
DROP FUNCTION [dbo].[Split]
END
GO
CREATE FUNCTION dbo.Split
(
#RowData nvarchar(MAX),
#SplitOn nvarchar(50)
)
RETURNS #RtnValue table
(
Id int identity(1,1),
Data nvarchar(MAX)
)
AS
BEGIN
Declare #Cnt int
DECLARE #tst varchar(MAX)
Set #Cnt = 1
While (Charindex(#SplitOn,#RowData)>0)
Begin
Select
#tst = ltrim(rtrim(Substring(#RowData,1,Charindex(#SplitOn,#RowData)-1)));
Insert Into #RtnValue (data)
Select
Data = ltrim(rtrim(Substring(#RowData,1,Charindex(#SplitOn,#RowData)-1)))
Set #RowData = Substring(#RowData,Charindex(#SplitOn,#RowData)+2,len(#RowData))
Set #Cnt = #Cnt + 1
End
Insert Into #RtnValue (data)
Select Data = ltrim(rtrim(#RowData))
Return
END
GO
-- test out the function
SELECT data
FROM dbo.Split('
begin transaction;
go
alter table activity_log add
hcm_got_estimate_num char(16) default (NULL);
go
set ANSI_NULLS on;
go
commit;
go'
, 'go');
The idea is to add carriage return to the 'go' in "split-on" parameter. Unfortunately split doesn't work very well on such combination (some artifacts remain). So in order not to mess with the Split function you can prep the text by replacing carriage return + 'go' with some special character and then do the split on that character:
SELECT data
FROM dbo.Split(REPLACE('
begin transaction;
go
alter table activity_log add
hcm_got_estimate_num char(16) default (NULL);
go
set ANSI_NULLS on;
go
commit;
go',char(13) + char(10) + 'go', '¬')
, '¬');

Convert Varchar To Time Range

I Have 3 varchar Time Range and it should be Converted to start & Finish time value,
here's the value :
SCH
- 9:00-12:00
- 13-15:00
- 15-17:30
so I tried by myself to split into start time and finish and convert to time value
here's my split Function :
CREATE FUNCTION dbo.Split
(
#RowData nvarchar(2000),
#SplitOn nvarchar(5)
)
RETURNS #RtnValue table
(
Id int identity(1,1),
Data nvarchar(100)
)
AS
BEGIN
Declare #Cnt int
Set #Cnt = 1
While (Charindex(#SplitOn,#RowData)>0)
Begin
Insert Into #RtnValue (data)
Select
Data = ltrim(rtrim(Substring(#RowData,1,Charindex(#SplitOn,#RowData)-1)))
Set #RowData = Substring(#RowData,Charindex(#SplitOn,#RowData)+1,len(#RowData))
Set #Cnt = #Cnt + 1
End
Insert Into #RtnValue (data)
Select Data = ltrim(rtrim(#RowData))
Return
END
and I get the start & Finish value by do this in my dev query , but when i tried to convert 15-17:30 , I Got an error Conversion, because the start value is only 15 :
declare #valueToParse varchar(20) = '15-17:30'
select #schtimestart = data from dbo.split(#valueToParse,'-') where id=1
select #schtimefinish = data from dbo.split(#valueToParse,'-') where id=2
SELECT CAST(#schtimestart AS time)
SELECT CAST(#schtimefinish AS time)
how to convert only one value as Time value, or is there any simple conversion?
I Already Fix my Split Function, so if the start time have no Minutes value so it's add automatically
here's my code
USE [Dispatch]
GO
/****** Object: UserDefinedFunction [dbo].[Split] Script Date: 25/10/2013 09:39:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
alter FUNCTION dbo.Split
(
#RowData nvarchar(2000),
#SplitOn nvarchar(5)
)
RETURNS #RtnValue table
(
Id int identity(1,1),
Data nvarchar(100)
)
AS
BEGIN
Declare #Cnt int
Set #Cnt = 1
declare #tmp as varchar(20)
While (Charindex(#SplitOn,#RowData)>0)
Begin
SET #tmp = ltrim(rtrim(Substring(#RowData,1,Charindex(#SplitOn,#RowData)-1)))
Insert Into #RtnValue (data)
Select Data = case when ISNUMERIC(SUBSTRING(#tmp,1,2)) = 1 AND ISNUMERIC(SUBSTRING(#tmp,4,2)) = 1 then #tmp else (#tmp + ':00') END
Set #RowData = Substring(#RowData,Charindex(#SplitOn,#RowData)+1,len(#RowData))
Set #Cnt = #Cnt + 1
End
Insert Into #RtnValue (data)
Select Data = ltrim(rtrim(#RowData))
Return
END

How to return the output of stored procedure into a variable in sql server

I want to execute a stored procedure in SQL Server and assign the output to a variable (it returns a single value) ?
That depends on the nature of the information you want to return.
If it is a single integer value, you can use the return statement
create proc myproc
as
begin
return 1
end
go
declare #i int
exec #i = myproc
If you have a non integer value, or a number of scalar values, you can use output parameters
create proc myproc
#a int output,
#b varchar(50) output
as
begin
select #a = 1, #b='hello'
end
go
declare #i int, #j varchar(50)
exec myproc #i output, #j output
If you want to return a dataset, you can use insert exec
create proc myproc
as
begin
select name from sysobjects
end
go
declare #t table (name varchar(100))
insert #t (name)
exec myproc
You can even return a cursor but that's just horrid so I shan't give an example :)
You can use the return statement inside a stored procedure to return an integer status code (and only of integer type). By convention a return value of zero is used for success.
If no return is explicitly set, then the stored procedure returns zero.
CREATE PROCEDURE GetImmediateManager
#employeeID INT,
#managerID INT OUTPUT
AS
BEGIN
SELECT #managerID = ManagerID
FROM HumanResources.Employee
WHERE EmployeeID = #employeeID
if ##rowcount = 0 -- manager not found?
return 1;
END
And you call it this way:
DECLARE #return_status int;
DECLARE #managerID int;
EXEC #return_status = GetImmediateManager 2, #managerID output;
if #return_status = 1
print N'Immediate manager not found!';
else
print N'ManagerID is ' + #managerID;
go
You should use the return value for status codes only. To return data, you should use output parameters.
If you want to return a dataset, then use an output parameter of type cursor.
more on RETURN statement
Use this code, Working properly
CREATE PROCEDURE [dbo].[sp_delete_item]
#ItemId int = 0
#status bit OUT
AS
Begin
DECLARE #cnt int;
DECLARE #status int =0;
SET NOCOUNT OFF
SELECT #cnt =COUNT(Id) from ItemTransaction where ItemId = #ItemId
if(#cnt = 1)
Begin
return #status;
End
else
Begin
SET #status =1;
return #status;
End
END
Execute SP
DECLARE #statuss bit;
EXECUTE [dbo].[sp_delete_item] 6, #statuss output;
PRINT #statuss;
With the Return statement from the proc, I needed to assign the temp variable and pass it to another stored procedure. The value was getting assigned fine but when passing it as a parameter, it lost the value. I had to create a temp table and set the variable from the table (SQL 2008)
From this:
declare #anID int
exec #anID = dbo.StoredProc_Fetch #ID, #anotherID, #finalID
exec dbo.ADifferentStoredProc #anID (no value here)
To this:
declare #t table(id int)
declare #anID int
insert into #t exec dbo.StoredProc_Fetch #ID, #anotherID, #finalID
set #anID= (select Top 1 * from #t)

Create function dynamically in a database

HI i need to create a function dynamically in a database..My procedure accepts Database name as a parameter, then i need to create this function dynamically in that DATABASE.
But i am unable to execute this..please help me.Regards in advance
Create procedure [dbo].[Sp_Insertfun]
(
#OrgName nvarchar(100)
)
AS BEGIN
Declare #orgdataInsertString nvarchar(max);
set #orgdataInsertString='Use '+#OrgName+'' ;
set #orgdataInsertString=#orgdataInsertString+char(13)+char(10)+'GO'+'
Create function dbo.[fn_GroupDisplay](#GroupID int)
RETURNS #Group TABLE
(
GrpPath nvarchar(max)
)
as
begin
declare #ParentId1 int
declare #ParentId2 varchar(50)
declare #ParentId3 varchar(50)
declare #parentId4 varchar(50)
declare #Text nvarchar(max)
set #ParentId3=''''
begin
set #ParentId1=(select ParentID from GroupDetails where GroupID=#GroupID)
set #ParentId4=(select GroupName from GroupDetails where GroupID=#GroupID)
while(#ParentId1>0)
begin
set #parentId2=(select GroupName from GroupDetails where GroupID=#ParentId1 )
set #ParentId3 = #ParentId2+ ''\'' + coalesce(#ParentId3,''')
set #ParentId1=(select ParentID from GroupDetails where GroupID=#ParentId1 )
end
set #Text=#ParentId3+#ParentId4
INSERT INTO #Group VALUES (#Text)
end
RETURN
end'
execute sp_executesql #query=#orgdataInsertString
print #orgdataInsertString
end