scanf and printf in SQL Server

Source: Internet
Author: User
Tags printf

There are two extended stored procedures in SQL Server that implement the scanf and printf features, and use them appropriately to simplify the SQL code significantly when extracting and stitching strings.

1, xp_sscanf, use it to decompose a relatively fixed string, which is good for tired of using a bunch of substring and charindex friends. For example, a few days ago a post on how to decompose the IP address, relatively concise and common code should be the following

Copy Code code as follows:


if (object_id (' F_getip ') is not null)


drop function F_getip


Go


create FUNCTION dbo. F_getip (@ IP varchar (100))


returns @ t table (a int, b int, c int, d int)


as


begin


SET @ IP = replace (@ IP, '. ', ')


Declare


@ S1 varchar (3), @ S2 varchar (3),


@ S3 varchar (3), @ S4 varchar (3)


exec xp_sscanf @ IP, '%s%s%s ', @ S1 output, @ s2 output, @ s3 output, @ S4 Output


INSERT INTO @ t SELECT @ S1, @ s2, @ s3, @ S4


return


End


Go


SELECT * FROM dbo. F_getip (' 192.168.0.1 ')


Go


/*


a b c D


----------- ----------- ----------- -----------


192 168 0 1


*/


2, xp_sprintf, with which you can splice a string without worrying too many plus signs are difficult to control, such as a dynamic execution of SQL statements stored procedures

Copy Code code as follows:


if (object_id (' P_select ') is not null)


drop proc P_select


Go


CREATE proc P_select (@ tb varchar (m), @ cols varchar (MB), @ Wherecol varchar (MB), @ value varchar (100))


as


begin


DECLARE @ s varchar (8000)


exec xp_sprintf @ s output, ' Select%s from%s where%s= '%s ', @ cols, @ TB, @ Wherecol, @ value


exec (@ s)


End


Go


exec p_select ' sysobjects ', ' id,xtype,crdate ', ' name ', ' P_select '


/*


ID xtype crdate


----------- ----- -----------------------


898102240 P 2009-08-18 03:01:51.153


*/
Related Article

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.