不想在Asp.net中直接嵌入代码,那就用存储过程。

像写普通的SQL语句那样,写了下面这几句话:

CREATE PROCEDURE [dbo].[INSERTNOTEPAD] 
@tablename nvarchar (16) ,--表名作为参数传入
@datea datetime,--时间日期型的参数,定义表的时候就是datetime类型
@weekday datetime , --时间日期型的参数,定义表的时候就是datetime类型
@title nvarchar (50)--普通的可变字符串

 
AS
begin
--插入语句
insert into @tablename (datea,weekday,title)  values(@datea,@weekday,@title)
end
GO

 
写完编译,报错:“错误137:必须声明变量@tablename”。
在前面已经声明过这个变量了。。。。
给@tablename套上了个“[]”,变成[@tablename]:编译自然不错,运行错:“对象名 '@tablename' 无效。”确实是这样,套上“[]”,就是普通的字符串了。

 
直接试表名呢?
CREATE PROCEDURE [dbo].[INSERTNOTEPAD] 
@tablename nvarchar (16) ,--表名作为参数传入
@datea datetime,--时间日期型的参数
@weekday datetime , --时间日期型的参数
@title nvarchar (50)--普通的可变字符串

 
AS
begin
--插入语句(表名可以不用加“[]”,加了也不错)
insert into [表名] (datea,weekday,title)  values(@datea,@weekday,@title)
end
GO
可以的。
怎样让表名做参数?网上搜搜,有点思路。
改成如下:
CREATE PROCEDURE [dbo].[INSERTNOTEPAD] 
@tablename nvarchar (16) ,
@datea datetime(16),
@weekday datetime (16),
@title nvarchar (50)

 
AS
declare @insertsql nvarchar(300)
begin
select @insertsql='insert into '+@tablename+' (datea,weekday,title) values('+''''+@datea+''''+','+''''+@weekday+''''+','+''''+@title+''''+')'
--print @insertsql//做打印用的
--打印出来的语句形式:
--insert into 表名 (datea,weekday,title) values('时间', '时间','字符串')
(这条语句在查询分析器中肯定正确:insert into 表名 (datea,weekday,title) values(getdate(),getdate(),'字符串'),类型都是匹配的)
exec(@insertsql)
end
GO


 

编译OK,运行报错,说datetime的类型转换有问题。如果在存储过程中不设置类型,在.Net中调用会怎样?

换类型:

@datea nvarchar(16),//把datetime换做字符
@weekday nvarchar (16)// /把datetime换做字符
在ASP.NET中调用,存储过程:
SqlConnectionStringBuildernew SqlConnectionStringBuilder();
BuilderConnectString.InitialCatalog = "XXX";
BuilderConnectString.IntegratedSecurity = false;
BuilderConnectString.UserID = "onthebox";
BuilderConnectString.Password = "onthebox";
BuilderConnectString.DataSource = "XXX";
SqlConnectionnew SqlConnection(BuilderConnectString.ConnectionString);
Connect_to_ XX.Open();
SqlCommandnew SqlCommand("INSERTNOTEPAD", Connect_to_ XX);
InsertCommand.CommandType = CommandType.StoredProcedure;
InsertCommand.Parameters.Add("@tablename", SqlDbType.VarChar, 16);
InsertCommand.Parameters.Add("@datea", SqlDbType.DateTime);//代码中的类型不需要变化
InsertCommand.Parameters.Add("@weekday", SqlDbType.DateTime);;//代码中的类型不需要变化
InsertCommand.Parameters.Add("@title", SqlDbType.VarChar, 50);
MembershipUserMembership.GetUser(Page.User.Identity.Name);
InsertCommand.Parameters["@tablename"].Value = Page.User.Identity.Name;
InsertCommand.Parameters["@datea"].Value = DateTime.Today;
InsertCommand.Parameters["@weekday"].Value = DateTime.Now;
InsertCommand.Parameters["@title"].Value = this.txtTitle.Text;
InsertCommand.ExecuteNonQuery();
Connect_to_XX.Close();

以上的存储过程和ASP.NET中代码结合起来是没有错的,类型转换都是正确的。

做SQL语句的时候应该是所有的东西都能直接换成字符串的形式去insert和update,SQL语义分析会转成相应的类型。从ASP.NET传过去的值都是object,怎么转都有型。

 

数据库弄的不好,漏洞大家说。

 

我们的生活需要力量。