0

我将 2 个联系电话存储在与 companycontactno 中的一个 companyID 对应的表中。桌子。我在存储过程中使用从 CSV 中提取值来做到这一点。

如果我想编辑那些与公司 ID 相对应的联系电话,我该怎么做?

这是我将用于编辑联系号码的存储过程..我在更新它时遇到了困难..请帮忙

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================

CREATE PROCEDURE dbo.EditCompanyDetails
(
@OldCompanyName varchar(max),
@NewCompanyName varchar(max),
@newAddress varchar(max),
@newMailID varchar(max),
@Temp varchar(8000)
)

AS
BEGIN
SET NOCOUNT ON;

declare @compID int

DECLARE @c int, @a varchar(max), @id int, @variable varchar(8000), @max int

DECLARE @Temp_Table table (serial_no int Identity(1,1), value varchar(max))

--PROCEDURE--

--Editing Company Table--
set @compID=(Select Company.CompanyID from Company where Company.CompanyName=@OldCompanyName)

update Company
set CompanyName=@NewCompanyName, [Address]=@newAddress, Email=@newMailID
where Company.CompanyID=@compID

--For CONTACT NUMBERS

    --Using Table to store CSV seperately in each row--
select @c = CHARINDEX(',', @Temp)

while @c > 0
BEGIN
    insert into @Temp_Table
    select LEFT(@Temp, @c - 1)

    select @Temp = right(@Temp, LEN(@Temp) - @c)
    select @c = CHARINDEX(',', @Temp)
END

--Update Table CompanyContactNo
  --CompanyContactNo have following Columns:
   --CNoID (PK)
   --CompanyID (references PK in Company table
   --ContactNumber

set @max= (select MAX(serial_no) from @Temp_Table)


while @max > 0
BEGIN
set @variable = (select value from @Temp_Table where serial_no=@max)

update CompanyContactNo
set ContactNumber=@variable
where CompanyID=@compID
set @max = @max-1
END

End

GO
4

1 回答 1

1

假设您只有 2 行,并且您知道 CompanyContactNo 表中有 2 个联系人行,您可以执行 2 个 Update 语句,每个语句都会影响不同的行:

UPDATE CompanyContactNo
Set ContactNumber=
    (SELECT value FROM @Temp_Table WHERE serial_no = (SELECT MAX(serial_no) FROM @Temp_Table))
WHERE 
    CompanyID=@compID
    AND (CNoId = select MAX(CNoId) FROM CompanyContactNo WHERE CompanyID = @compID)

然后是第二个联系电话:

UPDATE CompanyContactNo
SET ContactNumber=
        (SELECT value FROM @Temp_Table WHERE serial_no = (SELECT MIN(serial_no) FROM @Temp_Table))
WHERE 
    CompanyID=@compID
    AND (CNoId = select MIN(CNoId) FROM CompanyContactNo WHERE CompanyID = @compID)
于 2012-10-29T00:06:21.403 回答