Question

This is my dynamic query:

exec sp_executesql N'SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY NAME asc) peta_rn, peta_query.* 
    From (Select BOOK, PageINT, PageCHAR NAME, TYPE, PDF From test1 cdn
                            Inner Join test2 cwi
                                On cwi.ID = cdn.ID Where 1=1  And IsNull(NAME,'''') Like COALESCE(@0,'''') + ''%''  )
                                 as peta_query) peta_paged WHERE peta_rn>@1 AND peta_rn<=@2',N'@0 varchar(4000),@1 bigint,@2 bigint',@0='Miller',@1=0,@2=50

As you can see I am only searching for Miller but I get names which are empty too. What am I missing here? Any help would be appreciated.

Was it helpful?

Solution

I see a problem in your SQL expression that may be the source of the issue within the inner select:

From (Select BOOK, PageINT, PageCHAR NAME, TYPE, PDF From test1 cdn
    Inner Join test2 cwi
    On cwi.ID = cdn.ID 
    Where 1=1  And IsNull(NAME,'''') Like COALESCE(@0,'''') + ''%''  )

I believe in the predicate IsNull(NAME,'''') Like COALESCE(@0,'''') + ''%'' you're intending to reference PageCHAR NAME, but that is not happening.

The SELECT statement is one of the last parts to be executed, WHERE will execute first and have no idea about PageCHAR being aliased as NAME.

So if your intention is to use PageCHAR, change your predicate to IsNull(PageCHAR,'''') Like COALESCE(@0,'''') + ''%''.

Where the column NAME is coming from I have no idea. There may be a NAME column in your table somewhere, or maybe something super crazy is happening because NAME does exist outside the CTE, but I don't think that's it.

Also applying a function to the left side of a predicate will definitely make it not use an index, so be sure you really want to do that.

Here is a helpful link regarding the order of execution in a select statment: http://www.c-sharpcorner.com/Blogs/4536/order-of-execution-of-select-statement.aspx

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