我目前有以下存储过程;
CREATE PROCEDURE web.insertNewCampaign
(
@tmp_Id BIGINT,
@tmp_Title VARCHAR(100),
@tmp_Content VARCHAR(8000),
@tmp_Pledge DECIMAL(7,2),
--@tmp_Recipients BIGINT,
@tmp_Date DATETIME,
@tmp_Private BIT,
@tmp_Template BIGINT,
@tmp_AddyBook BIGINT
)
AS
declare @recipients BIGINT
declare @tmp_IDENTITY BIGINT
declare @fave BIGINT
declare @allocation VARCHAR(50)
--insert campaign data
BEGIN TRAN
SELECT @recipients = addMaster_NoRecipients FROM tbl_AddressBookMaster
WHERE addMaster_UserId = @tmp_Id AND addMaster_Key = @tmp_AddyBook;
INSERT INTO TBL_CAMPAIGNS ([campaign_MemberId], [campaign_Title], [campaign_Content], [campaign_Pledge], [campaign_Date], [campaign_Private], [campaign_Template], [campaign_AddressBook], [campaign_Recipients])
VALUES (@tmp_Id, @tmp_Title, @tmp_Content, @tmp_Pledge, @tmp_Date, @tmp_Private, @tmp_Template, @tmp_AddyBook, @recipients)
SELECT @tmp_IDENTITY = SCOPE_IDENTITY() --this returns the newly added IDENTITY ID
COMMIT
......
所以我有两个问题:
1)如何将@tmp_Pledge除以@recipients给@allocation,例如:(@ allocation = @tmp_Pledge / @recipients)
2)是否有可能将这些语句复合到一个更有效的语句中,并将@allocation有效地作为值插入到[campaign_RecipShare]列中,并减少对这些声明变量的需求?
非常感谢您为这两个问题提供的任何帮助。
- )
答案 0 :(得分:1)
在第一次选择后,您可以执行此操作来设置@allocation
:
set @allocation = @tmp_pledge / @recepients
至于提高效率,它已经相当有效 - 你不会经历任何更少的步骤,但你可以稍微压缩代码:
INSERT INTO TBL_CAMPAIGNS (
[campaign_MemberId], [campaign_Title], [campaign_Content],
[campaign_Pledge], [campaign_Date], [campaign_Private],
[campaign_Template], [campaign_AddressBook], [campaign_Recipients],
[capmain_RecipShare])
SELECT
@tmp_Id, @tmp_Title, @tmp_Content,
@tmp_Pledge, @tmp_Date, @tmp_Private,
@tmp_Template, @tmp_AddyBook, addMaster_NoRecipients,
@tmp_Pledge / addMaster_NoReceipients as Allocation
FROM
tbl_AddressBookMaster
WHERE
addMaster_UserId = @tmp_Id
AND addMaster_Key = @tmp_AddyBook
SELECT @tmp_IDENTITY = SCOPE_IDENTITY() --this returns the newly added IDENTITY ID
这也使您无需计算@allocation
语句之外的insert
成员。
答案 1 :(得分:1)
1)@tmp_pledge / @recepients - 我假设分配是TBL_CAMPAIGNS中某个形式的数字字段,在varchar中保存一个数字并不是一个好主意。
2)你只需要构建一个select,它返回另一个表中的所有值以及与要插入的列匹配的参数。
insert into TBL_CAMPAIGNS ([campaign_MemberId], [campaign_Title], [campaign_Content], [campaign_Pledge], [campaign_Date], [campaign_Private], [campaign_Template], [campaign_AddressBook], [campaign_Recipients], [campaign_allocation)
select @tmp_Id, @tmp_Title, @tmp_Content, @tmp_Pledge, @tmp_Date, @tmp_Private, @tmp_Template, @tmp_AddyBook, addMaster_NoRecipients, @tmp_pledge / addMaster_NoRecipients
FROM FROM tbl_AddressBookMaster WHERE addMaster_UserId = @tmp_Id AND addMaster_Key = @tmp_AddyBook;
SELECT @tmp_IDENTITY = SCOPE_IDENTITY() - 这会返回新添加的IDENTITY ID
答案 2 :(得分:1)
set @allocation = @tmp_pledge / (@recepients* 1.0)
你想这样做,否则你将遇到整数数学,结果将舍入为整数。