code_junkie

String list in SqlCommand through Parameters in C#

Nov 10th, 2011
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. SELECT blahblahblah WHERE blahblahblah IN @LISTOFWORDS
  2.  
  3. DataTable dt = new DataTable();
  4. dt.Columns.Add("word", typeof(string));
  5. foreach (String word in listOfWords)
  6. {
  7. dt.Rows.Add(word);
  8. }
  9. comm.Parameters.Add("LISTOFWORDS", System.Data.SqlDbType.Structured).Value = dt;
  10.  
  11. SELECT * FROM [Table] WHERE ID IN (1,2,3)
  12.  
  13. SELECT * FROM [Table] WHERE ID IN ( SELECT TableID FROM [OtherTable] WHERE OtherTableID= @OtherTableID )
  14.  
  15. StringBuilder sb = new StringBuilder();
  16. for (int i=0; i< listOfWords.Count; i++)
  17. {
  18. sb.AppendFormat("p{0},",i);
  19. comm.Parameters.AddWithValue("p"+i.ToString(), listOfWords[i]);
  20. }
  21.  
  22. comm.CommandText = string.Format(""SELECT blahblahblah WHERE blahblahblah IN ({0})",
  23. sb.ToString().TrimEnd(','));
  24.  
  25. SELECT blah WHERE blah IN (p0,p1,p2,p3...)...p0='aaa',p1='bbb'
  26.  
  27. ALTER FUNCTION [dbo].[Split]
  28. (
  29. @RowData nvarchar(max),
  30. @SplitOn nvarchar(5) = ','
  31. )
  32. RETURNS @RtnValue table
  33. (
  34. Id int identity(1,1),
  35. Data nvarchar(100)
  36. )
  37. AS
  38. BEGIN
  39. Declare @Cnt int
  40. Set @Cnt = 1
  41.  
  42. While (Charindex(@SplitOn,@RowData)>0)
  43. Begin
  44. Insert Into @RtnValue (data)
  45. Select
  46. Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))
  47.  
  48. Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
  49. Set @Cnt = @Cnt + 1
  50. End
  51.  
  52. Insert Into @RtnValue (data)
  53. Select Data = ltrim(rtrim(@RowData))
  54.  
  55. Return
  56. END
  57.  
  58. Select Id, Data from dbo.Split('123,234,345,456',',')
  59.  
  60. CREATE PROCEDURE [dbo].[findDuplicates]
  61. @ids nvarchar(max)
  62. as
  63. begin
  64. select ID
  65. from SomeTable with (nolock)
  66. where ID in (select Data from dbo.Split(@ids,','))
  67. end
  68.  
  69. public void SomeFunction(List<int> ids)
  70. {
  71. var idsAsDelimitedString = string.Join(",", ids.Select(id => id.ToString()).ToArray());
  72.  
  73. // ... or however you make your connection
  74. var con = GetConnection();
  75.  
  76. try
  77. {
  78. con.Open();
  79.  
  80. var cmd = new SqlCommand("findDuplicates", con);
  81.  
  82. cmd.Parameters.Add(new SqlParameter("@ids", idsAsDelimitedString));
  83.  
  84. var reader = cmd.ExecuteReader();
  85.  
  86. // .... do something here.
  87.  
  88. }
  89. catch (Exception)
  90. {
  91. // catch an exception?
  92. }
  93. finally
  94. {
  95. con.Close();
  96. }
  97. }
Add Comment
Please, Sign In to add comment