如何通过CSV更新/编辑表格?

时间:2012-10-26 14:18:41

标签: sql-server-2008 csv stored-procedures

我在一个表中存储了2个联系号码,对应于companycontactno中的一个companyID。表。我是通过在存储过程中从CSV中提取值来实现的。

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

这是我将用于编辑联系号码的storedProcedure ..我很难更新它...请帮助

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

1 个答案:

答案 0 :(得分: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)