SQL Server: Where & Like Statements -


i'm rusty sql game. have code (see below) checks on database instance (instance001, instance002, etc), looks when last_read , last_write fields null, along when last reset. nothing on top.

the issue i'm having how execute across multiple instances. you'll see commented out section. if add in appropriate or statement (or inst_name 'instance002'), isn't getting results seeking.

example: instance001 yields 1 records. instance002 yields 60. if use where inst_name 'instance001' or inst_name 'instance002' 210 records. how manipulate sql provide 61?

declare @timestring nvarchar(50) = convert(varchar(24), getdate(), 120) select db_name, inst_name, min([last_srvr_rst]) min_srvr_rst, last_read, last_write, log_date=@timestring cms_db_last_read_write     -- targeted db data. inst_name                 -- targeted instance(s)     'instance001'     /*     'instance002'     'instance003'       'instance004'     */     , last_read null       -- both read , write must null     , last_write null      -- show no activity.     --and [last_srvr_rst] = min([last_srvr_rst]) group db_name, inst_name, last_srvr_rst, last_read, last_write 

and takes precedence on or, need group 2 conditions using parenthesis:

... (inst_name = 'instance001' or inst_name = 'instance002') ,   last_read  null  ,   last_write null group ...  

note: changed usage like =, looking exact match, , doesn't make sense use like in situation.

the reason grouping due precedence order mentioned above. order is:

level   operators 1       ~ (bitwise not) 2       * (multiply), / (division), % (modulo) 3       + (positive), - (negative), + (add), (+ concatenate), - (subtract), & (bitwise and), ^ (bitwise exclusive or), | (bitwise or) 4       =, >, <, >=, <=, <>, !=, !>, !< (comparison operators) 5       not 6       , 7       all, any, between, in, like, or, 8       = (assignment) 

what means is, of and statements evaluated first. after have been evaluated, or statement evaluated.

this makes query more compiler:

where    (         inst_name = 'instance001' ,     last_read  null ,     last_write null ) or      inst_name = 'instance002' 

which why getting 210 results, opposed expected 61, pulling in all records in instance002, disregarding other where filters.

rewriting query grouping 2 conditions mentioned above compiler instead:

where    (         last_read  null ,     last_write null ) ,       (                inst_name = 'instance002' or      inst_name = 'instance001' ) 

which should logical conditions expecting.


another alternative way can write query without and/or grouping altogether using in clause:

... inst_name in ('instance001', 'instance002') ,   last_read null ,   last_write null group ... 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -