views:

159

answers:

1

Hi

I want to realize a query with the Visual Studio 2008 build in Query Builder for a TableAdapter similar like following (MSSQL 2008):

select * from [MyDB].[dbo].[MyView] where UNIQUE_ID NOT IN ('MyUniqueID1','MyUniqueID2')

How do I have to set the Filter in my query in order to call it with the myTableAdapter.GetDataExceptUniqueIds(...) function?

I tried to set the filter to NOT IN (@ids) and called it with

string[] uniqueIds = ...;
myTableAdapter.GetDataExceptUniqueIds(String.Join("','", uniqueIds));

and with

StringBuilder sb = new StringBuilder("'");
sb.Append(String.Join("','", uniqueIds));
sb.Append("'");
return myTableAdapter.GetDataExceptUniqueIds(sb.ToString());

but both failed

A: 

You cannot use dynamic parameters in a SELECT ... WHERE [NOT] IN list

WORKAROUND:

Create a table function, similar to the following function:

CREATE FUNCTION dbo.ParmsToTable(@Parameters varchar(4000))
returns @result TABLE (Value varchar(100))
AS  
begin
     DECLARE @pTable table
          (
          Value varchar(100)
          )

     DECLARE @Value varchar(100), @Pos int

     SET @Parameters = LTRIM(RTRIM(@Parameters))+ ','
     SET @Pos = CHARINDEX(',', @Parameters, 1)

     IF REPLACE(@Parameters, ',', '') <> ''
     BEGIN
          WHILE @Pos > 0
          BEGIN
               SET @Value = LTRIM(RTRIM(LEFT(@Parameters, @Pos - 1)))
               IF @Value <> ''
               BEGIN
                    INSERT INTO @pTable (Value) VALUES (@Value) 
               END
               SET @Parameters = RIGHT(@Parameters, LEN(@Parameters) - @Pos)
               SET @Pos = CHARINDEX(',', @Parameters, 1)

          END
     END    
     INSERT @result
     SELECT value
        FROM @pTable 
     RETURN
END    

and change your TableAdapter as follows:

select * from [MyDB].[dbo].[MyView] where UNIQUE_ID NOT IN
(select value from dbo.ParmsToTable(@p)  )
Noah