我只想执行一次存储过程,但每次都从临时表#tbl_schools传递不同的参数值。我怎样才能完成这项任务?
create table #tbl_schools(id int not null)
insert into #tbl_schools(id) values (1)
insert into #tbl_schools(id) values (2)
insert into #tbl_schools(id) values (3)
insert into #tbl_schools(id) values (4)
insert into #tbl_schools(id) values (5)
insert into #tbl_schools(id) values (6)
insert into #tbl_schools(id) values (7)
select * from #tbl_schools nolock
go-----------
create proc sp_Prac @id int
as
print 'ID is: ' + cast(@id as varchar(10)) + char(10)
go-----------
exec sp_Prac @id = select id from #tbl_schools -- This part errors out.
答案 0 :(得分:0)
试试这个答案:
CREATE TABLE #tbl_schools(id INT NOT NULL)
INSERT INTO #tbl_schools(id) VALUES (5)
INSERT INTO #tbl_schools(id) VALUES (13)
INSERT INTO #tbl_schools(id) VALUES (1)
INSERT INTO #tbl_schools(id) VALUES (7)
INSERT INTO #tbl_schools(id) VALUES (2)
INSERT INTO #tbl_schools(id) VALUES (8)
INSERT INTO #tbl_schools(id) VALUES (4)
SELECT * FROM #tbl_schools NOLOCK
GO-----------
CREATE PROC sp_Prac @id INT
AS
PRINT 'ID is: ' + CAST(@ID AS VARCHAR(10)) + CHAR(10)
GO-----------
DECLARE @MAX INT, @MIN INT, @CurValue INT
SELECT *,ROW_NUMBER() OVER(ORDER BY id)RN
INTO #MyTable
FROM #tbl_schools
SELECT @MAX=MAX(RN),@MIN=MIN(RN) FROM #MyTable
WHILE @MIN<=@MAX
BEGIN
SELECT @CurValue=ID FROM #MyTable WHERE RN=@MIN
EXEC sp_Prac @id = @CurValue
SET @MIN=@MIN+1
END
DROP TABLE #tbl_schools
DROP TABLE #MyTable
<强>结果:强>
ID is: 1
ID is: 2
ID is: 4
ID is: 5
ID is: 7
ID is: 8
ID is: 13