我已经创建了一个SQL脚本来循环抛出数据库并创建一个函数(该函数的目的是将RTF转换为纯文本)。 我将函数创建的脚本放在变量上,然后尝试使用exec命令执行它。
我使用了While循环,并将请求放置在varchar变量上,然后exec @command
但我收到此错误:
declare @Total as int
select @Total = count(*) from Temp1
declare @counter as int
set @counter = 1
declare @CurrentVal as varchar(max)
declare @command varchar(max)
while (@counter <= @Total)
begin
select @CurrentVal = name from Temp1 where RowId = @counter
set @command=' use '+@CurrentVal+'
GO
CREATE FUNCTION dbo.fnParseTEXTRTF
(
@rtf VARCHAR(max)
)
RETURNS VARCHAR(max)
AS
BEGIN
DECLARE @Stage TABLE
(
Chr CHAR(1),
Pos INT
)
INSERT @Stage
(
Chr,
Pos
)
SELECT SUBSTRING(@rtf, Number, 1),
Number
FROM master..spt_values
WHERE Type = ''p''
AND SUBSTRING(@rtf, Number, 1) IN (''{'', ''}'')
DECLARE @Pos1 INT,
@Pos2 INT
SELECT @Pos1 = MIN(Pos),
@Pos2 = MAX(Pos)
FROM @Stage
DELETE
FROM @Stage
WHERE Pos IN (@Pos1, @Pos2)
WHILE 1 = 1
BEGIN
SELECT TOP 1 @Pos1 = s1.Pos, @Pos2 = s2.Pos
FROM @Stage AS s1
INNER JOIN @Stage AS s2 ON s2.Pos > s1.Pos
WHERE s1.Chr = ''{''
AND s2.Chr = ''}''
ORDER BY s2.Pos - s1.Pos
IF @@ROWCOUNT = 0
BREAK
DELETE
FROM @Stage
WHERE Pos IN (@Pos1, @Pos2)
UPDATE @Stage
SET Pos = Pos - @Pos2 + @Pos1 - 1
WHERE Pos > @Pos2
SET @rtf = STUFF(@rtf, @Pos1, @Pos2 - @Pos1 + 1, '''')
END
SET @Pos1 = PATINDEX(''%\cf[0123456789][0123456789 ]%'', @rtf)
WHILE @Pos1 > 0
SELECT @Pos2 = CHARINDEX('' '', @rtf, @Pos1 + 1), @rtf = STUFF(@rtf, @Pos1, @Pos2 - @Pos1 + 1, ''''), @Pos1 = PATINDEX(''%\cf[0123456789][0123456789 ]%'', @rtf)
SELECT @rtf = REPLACE(@rtf, ''\pard'', ''''), @rtf = REPLACE(@rtf, ''\par'', ''''), @rtf = case when LEN(@rtf)>0 then LEFT(@rtf, LEN(@rtf) - 1) else @rtf end
SELECT @rtf = REPLACE(@rtf, ''\b0 '', ''''), @rtf = REPLACE(@rtf, ''\b '', '''')
SELECT @rtf = STUFF(@rtf, 1, CHARINDEX('' '', @rtf), '''')
RETURN @rtf
end'
set @counter = @counter + 1
exec @command
end
答案 0 :(得分:0)
据我了解,函数正确,这是跨多个数据库执行函数创建语句的主要问题。 GO不能在这里使用,它不是sql,它是客户端执行范围内所有语句的指令 不幸的是,不能使用[DatabaseName]。[schema]。[FuncName]在当前数据库中创建函数。 我可以提出这样的技术来解决问题,仅以代码为例
declare @funccode nvarchar(4000);
set @funccode='CREATE FUNCTION [dbo].[fntest]
(
)
RETURNS int
AS
BEGIN
RETURN 1
END;'
declare @dbname nvarchar(100)='TestDatabase'
declare @statement nvarchar(max) ='use '+@dbname+';
exec (@func);'
exec sp_executesql @stmt = @statement,@params=N'@func nvarchar(4000)',@func=@funccode;
想法-在已经设置了当前数据库的情况下,在exec语句内切换当前数据库并调用新的exec语句