sqlserver 預存程序動態參數調用實現代碼

來源:互聯網
上載者:User

只是做筆記,沒什麼!! 複製代碼 代碼如下:--建立測試表
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根據id查詢, 2根據性別查詢
@args XML -- 參數都寫到這裡吧
AS
BEGIN
DECLARE @id INT,@sex BIT
SET @id=@args.value('(args/id)[1]','int') --參數都可以寫在這裡,如果沒有傳過來,大不了是null值了,反正也用不到,沒關係的
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

參數寫xml裡感覺比用字串要好很多,這樣調用時參數就不好組織了,所以這裡要有個協助類XmlArgs 複製代碼 代碼如下: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();
}
}

調用: 複製代碼 代碼如下: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;
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.