存儲過程傳入一般的參數都很簡單,今天要說一下存儲過程傳入datatable 類型
首先要自定義一個 表類型
CREATE TYPE [dbo].[servicedatableType] AS TABLE ( category int NULL, class int NULL, packname nvarchar(1000) NULL, packid int NULL , serviceid int null, servicename nvarchar(500) null, serviceprice decimal(18,2) null, servicecomment nvarchar(4000) null, servicecategory int null, sstate int null, iscarray int null ) GO
我們自定義了表類型以后 在存儲過程中就可以 直接用了
@servicollection servicedatableType readonly
這里我們定義了一個 表結構的字段, 在 存儲過程調用的時候直接傳入 datatable 就行了。
new SqlParameter("@servicollection",dt)
這里再 介紹一個我自己寫的例子, 需求是將傳入的 databke 遍歷 驗證是否存在, 不存在則執行寫入,此處遍歷datable時 用了 游標
create procedure pr_InsertPackinfoandService( @category int, @packid int, @class int, @packname nvarchar(500), @price decimal(18,2), @comment nvarchar(4000), @status int, @chargestatus int, @conecssionprice decimal(18,2), @renewprice decimal(18,2), @statrtime datetime, @endtime datetime, @renewyers int, @renewtimes int, @buytimes int, @iscarry int, @servicollection servicedatableType readonly ) as declare @isCount int declare @pspackedid int declare @pscategory int declare @psclass int declare @pkname nvarchar(100) declare @serviceid nvarchar(100) declare @servicename nvarchar(300) declare @pscomment nvarchar(200) declare @servicecate int declare @serviceprice decimal(18,2) declare @psstatus int declare @psiscarry int begin set @isCount=(select COUNT(*) from t_packages_info where pi_category=@category and pi_class=@class and pi_packageid=@packid ) if(@isCount=0) --判斷套餐 是否存在 begin --執行添加操作 insert into t_packages_info (pi_category,pi_class,pi_packageid,pi_packname,pi_price,pi_comment,pi_status,pi_chargestatus,pi_ConcessionalPrice,pi_RenewPrice,pi_AvailableEndTime,pi_AvailableStartTime,pi_RenewYears,pi_RenewTimes,pi_BuyTimes,pi_IsCarray) values(@category,@class,@packid,@packname,@price,@comment,@status,@chargestatus,@conecssionprice,@renewprice,@endtime,@statrtime,@renewyers,@renewtimes,@buytimes,@iscarry) --執行添加服務 declare cur_serList cursor scroll For select category, class,packname,packid,servicename,serviceprice,servicecomment,servicecategory,sstate,iscarray from @servicollection fetch first from cur_serList into @pscategory,@psclass,@pkname ,@serviceid,@servicename,@serviceprice,@pscomment,@servicecate,@psstatus,@psiscarry While @@FETCH_STATUS=0 if((select COUNT(*) from t_package_service where ps_serviceid=@serviceid and pi_class=@psclass and pi_category=@pscategory )=0) begin --執行添加操作 insert into t_package_service(pi_category,pi_packageid,pi_class,pi_packname,ps_serviceid,ps_servicename,ps_serviceprice,ps_comment,ps_ServiceCategory,ps_State,ps_IsCarray) values(@pscategory,@pspackedid, @psclass,@pkname,@serviceid,@servicename,@serviceprice,@pscomment,@servicecate,@psstatus,@psiscarry) end fetch next from cur_serList into @pscategory,@psclass,@pkname ,@serviceid,@servicename,@serviceprice,@pscomment,@servicecate,@psstatus,@psiscarry end end Close cur_serList;----關閉游標 deallocate cur_serList ------刪除游標
