如何在循环中迭代地运行过程

时间:2013-12-25 19:21:38

标签: sql-server

我有一个加密字符串的过程。如何将其应用于表格以便我可以加密所有文本?

-- create table
create table TheTable
(word varchar(200),
 num int)
go

bulk insert TheTable
from 'E:\My documents\Desktop\testdata.txt'
with
(
fieldterminator = ',',
rowterminator = '\n'
)
go

--procedure
create procedure encrypt 
  @ptext as varchar(500)
  , @etext as varchar(500) OUTPUT
as 
begin
set nocount on
declare @key as tinyint = 3
declare @pc as varchar(1)
declare @i as smallint = 1
declare @n as smallint

set @n = len(@ptext)
set @etext = ' '

while @i <= @n
begin 
set @pc = substring (@ptext, @i, 1)

if ascii(@pc) between 48 and 57 
begin
    if ascii(@pc) + @key < 58
        set @pc = char((ascii(@pc) + @key))
    else 
        set @pc = char((ascii(@pc) + @key)-10)
end

else if ascii(@pc) between 65 and 90 
begin
    if ascii(@pc) + @key < 91
        set @pc = char((ascii(@pc) + @key))
    else 
        set @pc = char((ascii(@pc) + @key)-26)
end

if ascii(@pc) between 97 and 122 
begin
    if ascii(@pc) + @key < 123
        set @pc = char((ascii(@pc) + @key))
    else 
        set @pc = char((ascii(@pc) + @key)-26)
end

set @etext = @etext + @pc
set @i = @i + 1
end 
end

我听说光标不是一个好主意,所以我想在循环中运行所有单元格。我写了这样的东西,但它不起作用。

declare @ptext varchar(200)
declare @totalrow int
declare @rownum int
set  @totalrow = @@ROWCOUNT 
set @rownum = 1 

while @rownum <= @totalcount
begin 
declare @etext char(500);
exec encrypt @ptext, @etext OUT
select @etext 
set @rownum = @rownum + 1 
end
end

我该怎么办?感谢。

1 个答案:

答案 0 :(得分:1)

这应该这样做,一个例子

Declare @Counter int;
Set @Counter = 1;

While @Counter < 10
Begin    
    exec [dbo].[myprocedure] @param1,@param2                    
    Set @Counter = @Counter + 1;
End

找到这个帖子,几乎就是你要找的。

http://social.msdn.microsoft.com/Forums/en-US/344435d2-a009-4714-b739-8ea0ead636d2/calling-stored-procedure-in-a-loop-and-get-results