sqlserver 存儲過程動態(tài)參數(shù)調(diào)用實現(xiàn)代碼
發(fā)布日期:2022-01-23 12:14 | 文章來源:源碼之家
復(fù)制代碼 代碼如下:
--創(chuàng)建測試表
CREATE TABLE [dbo].[Student](
[ID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[Name] [nvarchar](20) NOT NULL DEFAULT (''),
[Age] [int] NOT NULL DEFAULT (0),
[Sex] [bit] NOT NULL DEFAULT (0),
[Address] [nvarchar](200) NOT NULL DEFAULT ('')
)
--比如是一個查詢存儲過程
Create PROC GetStudentByType
@type int =0, -- 1根據(jù)id查詢, 2根據(jù)性別查詢
@args XML -- 參數(shù)都寫到這里吧
AS
BEGIN
DECLARE @id INT,@sex BIT
SET @id=@args.value('(args/id)[1]','int') --參數(shù)都可以寫在這里,如果沒有傳過來,大不了是null值了,反正也用不到,沒關(guān)系的
SET @sex =@args.value('(args/sex)[1]','bit')
IF(@type=1)
BEGIN
SELECT * FROM dbo.Student WHERE ID=@id
END
IF(@type=2)
BEGIN
SELECT * FROM dbo.Student WHERE Sex=@sex
END
END
參數(shù)寫xml里感覺比用字符串要好很多,這樣調(diào)用時參數(shù)就不好組織了,所以這里要有個幫助類XmlArgs
復(fù)制代碼 代碼如下:
public class XmlArgs
{
private string _strArgs = string.Empty;
private bool _isCreate = false;
private Dictionary<string, string> _args;
public string Args
{
get
{
if (!_isCreate)
{
_strArgs = _CreateArgs();
_isCreate = true;
}
return _strArgs;
}
}
public XmlArgs()
{
_args = new Dictionary<string, string>();
}
public void Add(string key, object value)
{
_args.Add(key, value.ToString());
_isCreate = false;
}
public void Remove(string key)
{
_args.Remove(key);
_isCreate = false;
}
public void Clear()
{
_args.Clear();
_isCreate = false;
}
private string _CreateArgs()
{
if (_args.Count == 0)
{
return string.Empty;
}
StringBuilder sb = new StringBuilder();
foreach (string key in _args.Keys)
{
sb.AppendFormat("<{0}>{1}</{0}>", key, _args[key]);
}
return sb.ToString();
}
}
調(diào)用:
復(fù)制代碼 代碼如下:
private void BindData()
{
XmlArgs args = new XmlArgs();
args.Add("id", 1);
System.Data.DataTable dt = GetStudentByType(1, args);
GridView1.DataShow(dt);
}
private System.Data.DataTable GetStudentByType(int type, XmlArgs args)
{
SqlHelper helper = new SqlHelper();
helper.Params.Add("type", type);
helper.Params.Add("args", args.Args);
System.Data.DataTable dt = helper.RunDataTable("GetStudentByType");
return dt;
}
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
相關(guān)文章