淺析SQLServer中的Scanf與Printf_MsSql

來源:互聯網
上載者:User
SQLServer中有兩個擴充預存程序實現Scanf和Printf功能,恰當的使用它們可以在提取和拼接字串時大幅度簡化SQL代碼。

1、xp_sscanf,用它可以分解格式相對固定的字串,這對於厭倦使用一堆substring和charindex的朋友來說不錯。比如前幾天的一個文章中提出的如何分解ip地址,相對簡練且通用的代碼應該是下面這樣
複製代碼 代碼如下:

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 %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,用它可以拼接出一個字串而不用擔心過多的加號很引號難以控制,比如一個動態執行sql語句的預存程序
複製代碼 代碼如下:

if (object_id ('p_select' ) is not null )
drop proc p_select
go
create proc p_select (@ tb varchar (100 ), @ cols varchar (100 ), @ wherecol varchar (100 ), @ 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
*/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.