Question

I have table IteamMaster and query as below,

 Select ItemID from ItemMaster 
 Where ItemID IN(1,2,...,100)

this query returns me the all the values from the table which are available now what i want is the query should return the itemID which are not present in the table that is suppose My table has data as

  ItemId        ItemName
   1               x
   3               y
   4               z
   10              a

then it must return me the all the item id's except 1,3,4,10 from set of IN() conditions value ? How to get that values any help would be great ? And my values are dynamically generating and pass to the query query is also dynamically genrated

Was it helpful?

Solution

You can't magic values up out of no-where. Whatever you select FROM must contain the value you want. Using the system table master..spt_value you can generate a long list of values, and check for numbers that are in there, but not in your table...

;With Numbers as (
    select ROW_NUMBER() OVER (ORDER BY number) as n
    from master..spt_values
)

SELECT
  *
FROM
  Numbers
LEFT JOIN
  yourTable
    ON  Numbers.n = yourTable.ItemId
WHERE
      Numbers.n IN (1,2,...,100)
  AND yourTable.ItemID IS NULL

Or...

;With Numbers as (
    select ROW_NUMBER() OVER (ORDER BY number) as n
    from master..spt_values
)

SELECT
  *
FROM
  Numbers
WHERE
      Numbers.n IN (1,2,...,100)
  AND NOT EXISTS (SELECT * FROM yourTable WHERE ItemID = Numbers.n)

There are hundreds of ways of creating that initial list of numbers. But create it you must. Until you have the list of numbers than can exist, you can't select the numbers that don't currently exist.

OTHER TIPS

What about this?

Select ItemID from ItemMaster Where ItemID NOT IN(1,2,...,100)

If you want to pass a list of values and obtain only values not in your table you can pass them as values and then exclude values already in your table. As follows:

Select * from (values 1,2,...,100) except Select ItemID from ItemMaster 

Update: this is db2 tested version, for sql server I needed to change a bit:

Select * from (values (1),(2),...,(100)) as temp(int) except Select ItemID from ItemMaster 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top