我有一个网站,客户订购的东西在线,在购物车模型等
问题是当我知道订单被记录时,有不同的信息需要更新,如订单表中的条目,从库存表中扣除,更新销售表等,我目前是通过运行每个单个查询一次到数据库根据需求修改其结果,然后运行另一个查询来更新结果,因为下一个查询需要前一个查询的信息:
bool stts = false; int re1 = 0,re2 = 0,re3 = 0; short maxOr = 0,maxCa = 0,maxOc = 0; sqlConnection conn= Shared.GetsqlCon(); //Make connection object conn= Shared.GetsqlCon(); var comm1 = new Commmand("SELECT MAX(orId) FROM [order];",sqlCon); maxOr = Shared.OSC(sqlCon,comm1); Shared.COC(sqlCon); //Close & Dispose connections conn= Shared.GetsqlCon(); var comm2 = new Commmand("SELECT MAX(caId) FROM [cart];",sqlCon); maxCa = Shared.OSC(sqlCon,comm2); Shared.COC(sqlCon); conn= Shared.GetsqlCon(); var comm3 = new Commmand("INSERT INTO [order_cart](orId,caId) VALUES(@maxOr,@maxCa);",sqlCon); comm3.Parameters.AddWithValue("@maxOr",maxOr + 1); comm3.Parameters.AddWithValue("@maxCa",maxCa + 1);
当然,这在任何方面都不是一个很好的方法,它一次又一次地来到数据库,我认为通过sql Server存储过程进行它将是一个更好的主意.但即使在尝试并找到了很多东西之后,我找不到如何将查询结果存储在SP变量中并在其中使用的示例,有些像这样:
Declare @myVar int //Stored Procedure variable @myVar = SELECT MAX(caId) FROM [cart] //Getting query result in the variable INSERT INTO [order_cart](orId,@myVar); //Updating record through the variable return @myVar //return variable value to the program
这可以做到吗如果是,请问如何引导.
解决方法
嗯,这是可能的.这里有几个例子.
-- one way to do this DECLARE @Cnt int SELECT @Cnt = COUNT(SomeColumn) FROM TableName GROUP BY SomeColumn -- another way to do the same thing DECLARE @StreetName nvarchar(100) SET @StreetName = (SELECT Street_Name from Streets where Street_ID = 123) -- Assign values to several variables at once DECLARE @val1 nvarchar(20) DECLARE @val2 int DECLARE @val3 datetime DECLARE @val4 uniqueidentifier DECLARE @val5 double SELECT @val1 = TextColumn,@val2 = IntColumn,@val3 = DateColumn,@val4 = GuidColumn,@val5 = DoubleColumn FROM SoMetable