I am writing a function where I am passing a table valued parameter. In some of the cases table valued parameter can be empty.
So, my function looks like below-
CREATE FUNCTION [dbo].[testTableValueParam]
(
@created_date datetime = null
,@Ids dbo.IdList readonly
)
RETURNS TABLE
AS
RETURN
(
SELECT top 10
name
,scores
,mgr_name
from dbo.employee
where
created_date = @created_date
and
employeeId in (select empid from @Ids) --ignore this condition when @Ids is empty.
)
My table type is created as below-
CREATE TYPE [dbo].[IdList] AS TABLE(
[empid] [nvarchar](11) NULL
)
I am calling my function from a c# code.
There are cases when the table value parameter will be empty and in those cases, when the table value parameter is empty, i want to ignore the condition in where clause.
I went through some of the links while searching my answer and the answers suggested in earlier posts didn't fix my problem.
So, right now, when @Ids parameter is empty, it gives me no record.
In some of the post they suggested not to pass a parameter for table value at all, and it will automatically treat it as an empty table.
But I have cases when I need to pass the parameter with data.
Some of the answers suggested, using if exist(select 1 from @Ids)
But, I can not use if exist in my where clause.
Please provide any suggestions.
Your responses are much appreciated.
Thanks.
In some of the cases table valued parameter can be empty. CREATE FUNCTION [dbo]. [testTableValueParam] ( @created_date datetime = null ,@Ids dbo. IdList readonly ) RETURNS TABLE AS RETURN ( SELECT top 10 name ,scores ,mgr_name from dbo.
SELECT * FROM yourTableName WHERE yourSpecificColumnName IS NULL OR yourSpecificColumnName = ' '; The IS NULL constraint can be used whenever the column is empty and the symbol ( ' ') is used when there is empty value.
You can use the NOT EXISTS
operator something like....
CREATE FUNCTION [dbo].[testTableValueParam]
(
@created_date datetime = null
,@Ids dbo.IdList readonly
)
RETURNS TABLE
AS
RETURN
(
SELECT top 10
name
,scores
,mgr_name
from dbo.employee
where
(@created_date IS NULL OR created_date = @created_date)
and
(
NOT EXISTS (SELECT * FROM @Ids)
OR
employeeId in (select empid from @Ids)
)
)
CREATE FUNCTION [dbo].[testTableValueParam]
(
@created_date datetime = null
,@Ids dbo.IdList readonly
)
RETURNS TABLE
AS
RETURN
(
SELECT top 10
name
,scores
,mgr_name
from dbo.employee
where
created_date = @created_date
and
((select count(*) from @Ids) < 1 or employeeId in (select empid from @Ids))
employeeId in (select empid from @Ids) --ignore this condition when @Ids is empty.
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With