sqlserver 存儲進程靜態參數挪用完成代碼。本站提示廣大學習愛好者:(sqlserver 存儲進程靜態參數挪用完成代碼)文章只能為提供參考,不一定能成為您想要的結果。以下是sqlserver 存儲進程靜態參數挪用完成代碼正文
只是做筆記,沒甚麼!!
--創立測試表
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 @
[email protected]('(args/id)[1]','int') --參數都可以寫在這裡,假如沒有傳過去,年夜不了是null值了,橫豎也用不到,沒緊要的
SET @sex
[email protected]('(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;
}