code_junkie

Parameterizing a SQL IN clause?

Nov 12th, 2011
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.84 KB | None | 0 0
  1. select * from Tags
  2. where Name in ('ruby','rails','scruffy','rubyonrails')
  3. order by Count desc
  4.  
  5. select * from Tags
  6. where '|ruby|rails|scruffy|rubyonrails|'
  7. like '%|' + Name + '|%'
  8.  
  9. string[] tags = new string[] { "ruby", "rails", "scruffy", "rubyonrails" };
  10. const string cmdText = "select * from tags where '|' + @tags + '|' like '%|' + Name + '|%'";
  11.  
  12. using (SqlCommand cmd = new SqlCommand(cmdText)) {
  13. cmd.Parameters.AddWithValue("@tags", string.Join("|", tags);
  14. }
  15.  
  16. string[] tags = new string[] { "ruby", "rails", "scruffy", "rubyonrails" };
  17. string cmdText = "SELECT * FROM Tags WHERE Name IN ({0})";
  18.  
  19. string[] paramNames = tags.Select(
  20. (s, i) => "@tag" + i.ToString()
  21. ).ToArray();
  22.  
  23. string inClause = string.Join(",", paramNames);
  24. using (SqlCommand cmd = new SqlCommand(string.Format(cmdText, inClause))) {
  25. for(int i = 0; i < paramNames.Length; i++) {
  26. cmd.Parameters.AddWithValue(paramNames[i], tags[i]);
  27. }
  28. }
  29.  
  30. cmd.CommandText = "SELECT * FROM Tags WHERE Name IN (@tag0,@tag1,@tag2,@tag3)"
  31. cmd.Parameters["@tag0"] = "ruby"
  32. cmd.Parameters["@tag1"] = "rails"
  33. cmd.Parameters["@tag2"] = "scruffy"
  34. cmd.Parameters["@tag3"] = "rubyonrails"
  35.  
  36. CREATE TYPE dbo.TagNamesTableType AS TABLE ( Name nvarchar(50) )
  37.  
  38. string[] tags = new string[] { "ruby", "rails", "scruffy", "rubyonrails" };
  39. cmd.CommandText = "SELECT Tags.* FROM Tags JOIN @tagNames as P ON Tags.Name = P.Name";
  40.  
  41. // value must be IEnumerable
  42. cmd.Parameters.AddWithValue("@tagNames", tags).SqlDbType = SqlDbType.Structured;
  43. cmd.Parameters["@tagNames"].TypeName = "dbo.TagNamesTableType";
  44.  
  45. select ...
  46. where '|peanut|butter|' like '%|' + 'pe%ter' + '|%'
  47.  
  48. select ...
  49. where '|butter|peanut|' like '%|' + 'pe%ter' + '|%'
  50.  
  51. select ...
  52. where '|peanut|butter|'
  53. like '%|' + 'pe%ter' + '|%' escape ''
  54.  
  55. select ...
  56. where '|pe%ter|'
  57. like '%|' + REPLACE( 'pe%ter' ,'%','%') + '|%' escape ''
  58.  
  59. select ...
  60. where '|pe%t!r|'
  61. like '%|' + REPLACE(REPLACE( 'pe%t!r' ,'!','!!'),'%','!%') + '|%' escape '!'
  62.  
  63. select ...
  64. where '|p_%t!r|'
  65. like '%|' + REPLACE(REPLACE(REPLACE( 'p_%t!r' ,'$','$$'),'%','$%'),'_','$_') + '|%' escape '$'
  66.  
  67. DECLARE @tags
  68.  
  69. SET @tags = ‘ruby|rails|scruffy|rubyonrails’
  70.  
  71. select * from Tags
  72. where Name in (SELECT item from fnSplit(@tags, ‘|’))
  73. order by Count desc
  74.  
  75. CREATE FUNCTION [dbo].[fnSplit](
  76. @sInputList VARCHAR(8000) -- List of delimited items
  77. , @sDelimiter VARCHAR(8000) = ',' -- delimiter that separates items
  78. ) RETURNS @List TABLE (item VARCHAR(8000))
  79.  
  80. BEGIN
  81. DECLARE @sItem VARCHAR(8000)
  82. WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
  83. BEGIN
  84. SELECT
  85. @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),
  86. @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
  87.  
  88. IF LEN(@sItem) > 0
  89. INSERT INTO @List SELECT @sItem
  90. END
  91.  
  92. IF LEN(@sInputList) > 0
  93. INSERT INTO @List SELECT @sInputList -- Put the last item in
  94. RETURN
  95. END
  96.  
  97. var inValues = new [] { "ruby","rails","scruffy","rubyonrails" };
  98.  
  99. var results = from tag in Tags
  100. where inValues.Contains(tag.Name)
  101. select tag;
  102.  
  103. string[] names = new string[] {"ruby","rails","scruffy","rubyonrails"};
  104. var tags = dataContext.Query<Tags>(@"
  105. select * from Tags
  106. where Name in @names
  107. order by Count desc", new {names});
  108.  
  109. string[] names = new string[] {"ruby","rails","scruffy","rubyonrails"};
  110. var tags = from tag in dataContext.Tags
  111. where names.Contains(tag.Name)
  112. orderby tag.Count descending
  113. select tag;
  114.  
  115. ALTER FUNCTION [dbo].[fn_sqllist_to_table](@list as varchar(8000), @delim as varchar(10))
  116. RETURNS @listTable table(
  117. Position int,
  118. Value varchar(8000)
  119. )
  120. AS
  121. BEGIN
  122. declare @myPos int
  123. set @myPos = 1
  124.  
  125. while charindex(@delim, @list) > 0
  126. begin
  127. insert into @listTable(Position,Value)
  128. values(@myPos, left(@list, charindex(@delim, @list) - 1))
  129.  
  130. set @myPos = @myPos + 1
  131. if charindex(@delim, @list) = len(@list)
  132. insert into @listTable(Position, Value)
  133. values(@myPos, '')
  134. set @list = right(@list, len(@list) - charindex(@delim, @list))
  135. end
  136.  
  137. if len(@list) > 0
  138. insert into @listTable(Position, Value)
  139. values(@myPos, @list)
  140.  
  141. Return
  142.  
  143. @Name varchar(8000) = null // parameter for search values
  144.  
  145. select * from Tags
  146. where Name in (SELECT value From fn_sqllist_to_table(@Name,',')))
  147. order by Count desc
  148.  
  149. SELECT ...
  150. ...
  151. WHERE tag IN( @tag1, ISNULL( @tag2, @tag1 ), ISNULL( @tag3, @tag1 ), etc. )
  152.  
  153. with qry(n, names) as
  154. (select len(list.names) - len(replace(list.names, ',', '')) - 1 as n,
  155. substring(list.names, 2, len(list.names)) as names
  156. from (select ',Doc,Grumpy,Happy,Sneezy,Bashful,Sleepy,Dopey,' names) as list
  157. union all
  158. select (n - 1) as n,
  159. substring(names, 1 + charindex(',', names), len(names)) as names
  160. from qry
  161. where n > 1)
  162. select n, substring(names, 1, charindex(',', names) - 1) dwarf
  163. from qry;
  164.  
  165. select n, substr(name, 1, instr(name, ',') - 1) dwarf
  166. from (select n,
  167. substr(val, 1 + instr(val, ',', 1, n)) name
  168. from (select rownum as n,
  169. list.val
  170. from (select ',Doc,Grumpy,Happy,Sneezy,Bashful,Sleepy,Dopey,' val
  171. from dual) list
  172. connect by level < length(list.val) -
  173. length(replace(list.val, ',', ''))));
  174.  
  175. select pivot.n,
  176. substring_index(substring_index(list.val, ',', 1 + pivot.n), ',', -1) from (select 1 as n
  177. union all
  178. select 2 as n
  179. union all
  180. select 3 as n
  181. union all
  182. select 4 as n
  183. union all
  184. select 5 as n
  185. union all
  186. select 6 as n
  187. union all
  188. select 7 as n
  189. union all
  190. select 8 as n
  191. union all
  192. select 9 as n
  193. union all
  194. select 10 as n) pivot, (select ',Doc,Grumpy,Happy,Sneezy,Bashful,Sleepy,Dopey,' val) as list where pivot.n < length(list.val) -
  195. length(replace(list.val, ',', ''));
  196.  
  197. <cfset myvalues = "ruby|rails|scruffy|rubyonrails">
  198. <cfquery name="q">
  199. select * from sometable where values in <cfqueryparam value="#myvalues#" list="true">
  200. </cfquery>
  201.  
  202. CREATE FUNCTION dbo.fnParseArray (@Array VARCHAR(1000),@separator CHAR(1))
  203. RETURNS @T Table (col1 varchar(50))
  204. AS
  205. BEGIN
  206. --DECLARE @T Table (col1 varchar(50))
  207. -- @Array is the array we wish to parse
  208. -- @Separator is the separator charactor such as a comma
  209. DECLARE @separator_position INT -- This is used to locate each separator character
  210. DECLARE @array_value VARCHAR(1000) -- this holds each array value as it is returned
  211. -- For my loop to work I need an extra separator at the end. I always look to the
  212. -- left of the separator character for each array value
  213.  
  214. SET @array = @array + @separator
  215.  
  216. -- Loop through the string searching for separtor characters
  217. WHILE PATINDEX('%' + @separator + '%', @array) <> 0
  218. BEGIN
  219. -- patindex matches the a pattern against a string
  220. SELECT @separator_position = PATINDEX('%' + @separator + '%',@array)
  221. SELECT @array_value = LEFT(@array, @separator_position - 1)
  222. -- This is where you process the values passed.
  223. INSERT into @T VALUES (@array_value)
  224. -- Replace this select statement with your processing
  225. -- @array_value holds the value of this element of the array
  226. -- This replaces what we just processed with and empty string
  227. SELECT @array = STUFF(@array, 1, @separator_position, '')
  228. END
  229. RETURN
  230. END
  231.  
  232. SELECT * FROM dbo.fnParseArray('a,b,c,d,e,f', ',')
  233.  
  234. and ( {1}==0 or b.CompanyId in ({2},{3},{4},{5},{6}) )
  235.  
  236. int origCount = idList.Count;
  237. if (origCount > 5) {
  238. throw new Exception("You may only specify up to five originators to filter on.");
  239. }
  240. while (idList.Count < 5) { idList.Add(-1); } // -1 is an impossible value
  241. return ExecuteQuery<PublishDate>(getValuesInListSQL,
  242. origCount,
  243. idList[0], idList[1], idList[2], idList[3], idList[4]);
  244.  
  245. DECLARE @InputString varchar(8000) = 'ruby,rails,scruffy,rubyonrails'
  246.  
  247. SELECT @InputString = @InputString + ','
  248.  
  249. ;WITH RecursiveCSV(x,y)
  250. AS
  251. (
  252. SELECT
  253. x = SUBSTRING(@InputString,0,CHARINDEX(',',@InputString,0)),
  254. y = SUBSTRING(@InputString,CHARINDEX(',',@InputString,0)+1,LEN(@InputString))
  255. UNION ALL
  256. SELECT
  257. x = SUBSTRING(y,0,CHARINDEX(',',y,0)),
  258. y = SUBSTRING(y,CHARINDEX(',',y,0)+1,LEN(y))
  259. FROM
  260. RecursiveCSV
  261. WHERE
  262. SUBSTRING(y,CHARINDEX(',',y,0)+1,LEN(y)) <> '' OR
  263. SUBSTRING(y,0,CHARINDEX(',',y,0)) <> ''
  264. )
  265. SELECT
  266. *
  267. FROM
  268. Tags
  269. WHERE
  270. Name IN (select x FROM RecursiveCSV)
  271. OPTION (MAXRECURSION 32767);
  272.  
  273. declare @x xml
  274. set @x='<items>
  275. <item myvalue="29790" />
  276. <item myvalue="31250" />
  277. </items>
  278. ';
  279. With CTE AS (
  280. SELECT
  281. x.item.value('@myvalue[1]', 'decimal') AS myvalue
  282. FROM @x.nodes('//items/item') AS x(item) )
  283.  
  284. select * from YourTable where tableColumnName in (select myvalue from cte)
Add Comment
Please, Sign In to add comment