Getting several lines from a table in SQL Server and list them -
i have list vehicles likes this:
let's display cars ecus tms1 , c200. how do that?
i have inserted function:
set ansi_nulls on go set quoted_identifier on go create function [dbo].[splitstring] (@pstring nvarchar(4000), @pdelimiter nchar(1)) returns table schemabinding return e1(n) ( select 1 union select 1 union select 1 union select 1 union select 1 union select 1 union select 1 union select 1 union select 1 union select 1 ), --10e+1 or 10 rows e2(n) (select 1 e1 a, e1 b), --10e+2 or 100 rows e4(n) (select 1 e2 a, e2 b), --10e+4 or 10,000 rows max ctetally(n) (--==== provides "base" cte , limits number of rows right front -- both performance gain , prevention of accidental "overruns" select top (isnull(datalength(@pstring),0)) row_number() on (order (select null)) e4 ), ctestart(n1) (--==== returns n+1 (starting position of each "element" once each delimiter) select 1 union select t.n+1 ctetally t substring(@pstring,t.n,1) = @pdelimiter ), ctelen(n1,l1) as(--==== return start , length (for use in substring) select s.n1, isnull(nullif(charindex(@pdelimiter,@pstring,s.n1),0)-s.n1,8000) ctestart s ) --===== actual split. isnull/nullif combo handles length final element when no delimiter found. select itemnumber = row_number() over(order l.n1), item = substring(@pstring, l.n1, l.l1) ctelen l substring(@pstring, l.n1, l.l1) <> '' ; go
and created stored procedure:
alter procedure [db_ddladmin].[spgetvehicles] ( @ecu nvarchar(20), @identifiers nvarchar(20) ) begin select * db_ddladmin.view_vehiclereadouts ecu in (select item [dbo].[splitstring](@ecu,',') ) , identifier in (select item [dbo].[splitstring](@identifiers, ',')) end
and execute stored procedure query:
exec [db_ddladmin].[spgetvehicles] @ecu = 'ebs7,alm1', @identifiers = '88'
i list vehicles containing ecus , identifiers. thing display vehicles has both of ecus have written there , not vehicles has 1 of desired ecus. how do that?
you can aggregation , having
. idea count number of matches:
with items(item) ( select item dbo.splitstring(@ecu, ',') ) select ?? db_ddladmin.view_vehiclereadouts ecu in (select items.item items) group ?? having count(*) = (select count(*) items);
the ??
represents column specifies vehicle.
if there can duplicates in table, use count(distinct ecu)
rather count(*)
in having
clause.
Comments
Post a Comment