日期:2014-05-18  浏览次数:20736 次

SQL SERVER 存储过程有问
CREATE PROCEDURE [DBO].[usp_Insert] 
@F1 VARCHAR(300)=' ',
@F2 VARCHAR(12)=' '
AS

 
INSERT INTO TableName(F1,F2, DATES) VALUES(@F1,@F2,GETDATE())
GO

@F1的值是这样的:'B07100400731,B07100400732,B07100400733,B07100400734'

@F2的值就是一个固定的值,如:'A00000000001'

我想做的是通过循环将@F1的值以逗号分开,然后一个一个插入数据库,如:

INSERT INTO TableName(F1,F2, DATES) VALUES('B07100400731','A00000000001',GETDATE())

INSERT INTO TableName(F1,F2, DATES) VALUES('B07100400732','A00000000001',GETDATE())

INSERT INTO TableName(F1,F2, DATES) VALUES('B07100400733','A00000000001',GETDATE())

INSERT INTO TableName(F1,F2, DATES) VALUES('B07100400734','A00000000001',GETDATE())

存储过程里面怎么写这个循环呢?

------解决方案--------------------
大致思路:
SQL code

create proc [dbo].[usp_Insert]
@F1 VARCHAR(300)=' ',
@F2 VARCHAR(12)=' '
as
create table #t1
(
    col varchar(12)
)

set @F1=replace(@F1,',',''' union all select ''')
set @F1='insert into #t1 select '''+@F1+''''
exec (@F1)

insert into tablename
(
    F1,
    F2,
    DATES
)
select col,
       @F2,
       getdate()
from #t1

drop table #t1

------解决方案--------------------
SQL code
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go 
create table [tb]([F1] varchar(20),[F2] varchar(20),[DATES] datetime)

DECLARE @f1 VARCHAR(300)='B07100400731,B07100400732,B07100400733,B07100400734'
DECLARE @f2 VARCHAR(30)='A00000000001'
DECLARE @s VARCHAR(300)=@f1
WHILE CHARINDEX(',',@s)>0
BEGIN
    INSERT INTO dbo.tb VALUES  (LEFT(@s,CHARINDEX(',',@s)-1), @f2,GETDATE())
    SET @s=REPLACE(@s,LEFT(@s,CHARINDEX(',',@s)),'')
END

select * from [tb]