开发者

NOT IN statement for Visual Studio's Query Builder for TableAdapter

开发者 https://www.devze.com 2022-12-30 19:40 出处:网络
I want to realize a query with the Visual Studio 2008 build in Query Builder for a TableAdapter similar like following (MSSQL 2008):

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.J开发者_如何学Pythonoin("','", uniqueIds));

and with

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

but both failed


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)  )
0

精彩评论

暂无评论...
验证码 换一张
取 消