User-Defined Function usage

Source: Internet
Author: User
Application 1:

  1. -- Use Lyds # DB
  2. -- Select ID, count (TEST) from t_test group by id -- this is the effect of grouping.
  3. -- Data table
  4. ID (INT) test (nvarchar (50 ))
  5. 1 aaa
  6. 2 bbb
  7. 1 CCC
  8. 2 ddd
  9. -- Create a UDF
  10. Create Function DBO. f_str (@ id int)
  11. Returns varchar (8000)
  12. As
  13. Begin
  14. Declare @ r varchar (8000)
  15. Set @ r =''
  16. Select @ r = @ r + ',' + Test
  17. From t_test
  18. Where id = @ ID
  19. Return stuff (@ r, 1, 1, '') -- remove the first comma
  20. End
  21. -- Call a custom function
  22. Select ID, test = DBO. f_str (ID)
  23. From t_test
  24. Group by ID
  25. -- Output content
  26. Id Test
  27. 1 AAA, CCC
  28. 2 BBB, DDD
  1. The first custom function:
  2. Create Function DBO. f_first
  3. (
  4. @ ID int,
  5. @ Name nvarchar (20)
  6. )
  7. Returns varchar (8000)
  8. As
  9. Begin
  10. Declare @ r varchar (8000)
  11. Set @ r = @ name + @ ID -- Here + converts the numeric type to a number by default.
  12. Return @ r
  13. End
  14. Usage:
  15. Select DBO. f_first (2, '2') as returnstr

End

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.