Question

Code

CREATE TYPE [dbo].[IntListType] AS TABLE([Number] [int] NULL)
DECLARE @ids as IntListType;
DECLARE @TempIds as IntListType;    

Situation

I have a long long list of products which need to be filtered in a stored procedure. The filter is given as a User-Defined Table Type and each filter can be empty or full. I've attempted to create a single query for this, but it won't work if one of the filters is empty.

So I decided to create another User-Defined Table Type which only contains the column: Number.

Then, for each Filter type it will check wether it's empty IF (select filterName from @customtable) is not null and if so, it will query the product Id's which match that name and add it to the list of numbers.

If the next filter isn't emmpty, it will add the id's to a temp table, which in turn will be combined with the first table.

So far, I found this to be the most effective way to handle whether a filter is null or not. In any way it will get the id's I need!

Now, every filter will eventually perfrom the following code:

IF (select count(*) from @ids) > 0
BEGIN               
    IF(select count(*) from @TempIds)
    BEGIN
    delete from @ids
        where Number not in 
            (select C.Number 
            from @ids C 
            inner join @TempIds T on C.Number = T.Number)       
    END
END
ELSE
BEGIN
    insert into @ids
    select * from @TempIds
END
delete from @TempIds

Problem

I'm looking for a way to implement the last named code into a stored procedure which gives me back a list of IntListType. However, every implementation I have of @ids (declare @ids as IntListType) can't be set. (asinset @ids = @TempIds' > Will complain about 'Must declare the scalar variable @ids' aswell as '@TempIds')

How can I fix this?

Attempts

I've already attempted to skip this all by combining every table with inner join, outer join and other joins.. but in no way will I get the same result when any (or all) of the filters is empty.

As far as I can see, this is the only way to effectively progress every filter type, check if they are null or not, if not; process the results etc etc

Was it helpful?

Solution

In the part of the query you shared, there is no declaration of @ids or @TempIds. Can you add that part?

Apart from that, I think you should not be looking at a User-Defined Type: Can T-SQL function return user-defined table type?

Have a look at User-Defined Functions:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top