SQL Server How to limit text characters in column while still allowing unlimited HTML styles?

fxnxkyjh  于 2024-01-05  发布在  其他
关注(0)|答案(1)|浏览(118)

If I have a column for notes/comments in a table, what is an appropriate way / is there a way to store a limited number of characters (say 600) while still allowing for unlimited HTML style markup?

The only way I could think of is to enforce the limit at the backend but I'm concerned it might not be enough.

u3r8eeie

u3r8eeie1#

If your HTML is really (X)HTML, it is possible to use SQL Server XML data type and built-in XQuery language capabilities.

XQuery allows to retrieve textual data only excluding HTML tags.

Even embedded CSS <style>...</style> could be easily taken out of the equation.

SQL

  1. -- DDL and sample data population, start
  2. DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, notes XML);
  3. INSERT @tbl (notes) VALUES
  4. (N'<html>
  5. <head>
  6. <meta charset="utf-8" />
  7. <style>
  8. table {border-collapse: collapse; }
  9. th {background-color: #4CAF50; color: white;}
  10. th, td { text-align: center; padding: 8px;}
  11. tr.yellow td {background-color: yellow;}
  12. </style>
  13. </head>
  14. <body>
  15. <table border="1" cellpadding="10">
  16. <thead>
  17. <tr>
  18. <th>No.</th>
  19. <th>State</th>
  20. <th>City</th>
  21. </tr>
  22. </thead>
  23. <tbody>
  24. <tr align="center" valign="center" class="yellow">
  25. <td>1</td>
  26. <td>FL</td>
  27. <td>Miami</td>
  28. </tr>
  29. <tr align="center" valign="center">
  30. <td>2</td>
  31. <td>FL</td>
  32. <td>Orlando</td>
  33. </tr>
  34. <tr align="center" valign="center">
  35. <td>3</td>
  36. <td>TX</td>
  37. <td>Dallas</td>
  38. </tr>
  39. </tbody>
  40. </table>
  41. </body>
  42. </html>');
  43. -- DDL and sample data population, end
  44. SELECT t.*
  45. , textOnly, LEN(textOnly) AS LenTextOnly
  46. FROM @tbl AS t
  47. CROSS APPLY (SELECT notes.query('
  48. for $x in /html//*[local-name()!="style"]/text()
  49. return $x
  50. ').value('text()[1]', 'NVARCHAR(MAX)')) AS t1(textOnly);

Output

IDtextOnlyLenTextOnly
1No.StateCity1FLMiami2FLOrlando3TXDallas39
展开查看全部

相关问题