mantawolf

SqlServer String Operators

Apr 13th, 2015
281
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.46 KB | None | 0 0
  1. CREATE TABLE ##table1 (
  2.       Id INT
  3.     , text1 VARCHAR(50)
  4.     , text2 VARCHAR(50)
  5. );
  6. INSERT INTO ##table1 (
  7.       Id
  8.     , text1
  9.     , text2
  10. )
  11. VALUES
  12.       (1, 'This is a string to test against another string', 'Another string to concat')
  13.     , (2, 'This is a second string', '')
  14.     , (3, 'And a third string', '')
  15.     , (4, 'Some random string', '')
  16.     , (5, 'The istring containis the istring is iniside', '')
  17.  
  18. CREATE TABLE ##table2 (
  19.       Id INT
  20.     , text1 VARCHAR(50)
  21. );
  22.  
  23. INSERT INTO ##table2 (
  24.       Id
  25.     , text1
  26. )
  27. VALUES
  28.       (1, 'abc')
  29.     , (2, 'acc')
  30.     , (3, 'adc')
  31.     , (4, 'adac')
  32.     , (5, 'adcc')
  33.     , (6, 'cac')
  34.     , (7, 'daz')
  35.  
  36. -- + operator
  37. SELECT
  38.     text1 + text2 AS textConcatenation1
  39. FROM ##table1
  40. WHERE Id = 1
  41.  
  42. -- += operator
  43. DECLARE @t1 VARCHAR(50) = '';
  44. SET @t1 += 'Hello';
  45. SET @t1 += ' World';
  46.  
  47. SELECT @t1;
  48.  
  49. -- % operator, starts with
  50. SELECT Id, text1
  51. FROM ##table1
  52. WHERE text1 LIKE('this%')
  53.  
  54. -- % operator, contains
  55. SELECT Id, text1
  56. FROM ##table1
  57. WHERE text1 LIKE('%is%')
  58.  
  59. -- % operator, ends with
  60. SELECT Id, text1
  61. FROM ##table1
  62. WHERE text1 LIKE('%string')
  63.  
  64. -- % operator
  65. SELECT *
  66. FROM ##table2
  67. WHERE text1 LIKE('a%c')
  68.  
  69. -- _ operator
  70. SELECT *
  71. FROM ##table2
  72. WHERE text1 LIKE('a_c')
  73.  
  74. -- [] operator
  75. SELECT *
  76. FROM ##table2
  77. WHERE text1 LIKE('a[cd]c')
  78.  
  79. -- [] operator with a range
  80. SELECT *
  81. FROM ##table2
  82. WHERE text1 LIKE('a[b-d]c')
  83.  
  84. -- [^] operator
  85. SELECT *
  86. FROM ##table2
  87. WHERE text1 LIKE('a[^cd]c')
  88.  
  89. DROP TABLE ##table1
  90. DROP TABLE ##table2
Advertisement
Add Comment
Please, Sign In to add comment