Sql-Server-2008

使用者定義函式返回值

  • January 4, 2019

大家好,我有一個功能:

ALTER FUNCTION [dbo].[getContentURL]
(
   @VID    int,
   @accountID int
)
RETURNS VARCHAR(500)
AS
BEGIN


DECLARE @cTable varchar(50) = '[CONTENT_CONNECT].[dbo].CONTENT_' + CONVERT(varchar(5),@accountID)
   DECLARE @vTable varchar(50) = '[CONTENT_CONNECT].[dbo].VERSION_' + CONVERT(varchar(5),@accountID)
DECLARE @sql VARCHAR(max) =  ''
DECLARE @RETURN VARCHAR(500)
DECLARE @ParmDefinition VARCHAR(500)
SET @sql = '
   DECLARE @CompanyID int
   DECLARE @RETURN VARCHAR(500)
   DECLARE @ProjectNumber int
   DECLARE @ContentID int
   DECLARE @VersionNumber int
   DECLARE @FileName varchar(400)
 select @VersionNumber= V.Number,@ContentID= V.ContentID,@ProjectNumber=P.Number,@FileName=C.Name,@CompanyID=P.CompanyID 
   from ' + @vTable + ' V 
   inner join' + @cTable + ' C on V.ContentID=C.ID
   inner join Project P on C.ProjectID=P.ID where V.VID='+convert(varchar,@VID)+'

select ''/''+Convert(varchar,@CompanyID)+''/''+Convert(varchar,@ProjectNumber)+''/''+Convert(varchar,@ContentID)+''/''+Convert(varchar,@VersionNumber)+''/''+@FileName'


SET @ParmDefinition = N'@RETURN VARCHAR(500) OUTPUT'
   exec sp_executesql @sql, @ParmDefinition,  @RETURN OUTPUT
 set @RETURN=(select @RETURN)
RETURN @RETURN
END

但是當我執行這個功能時

select  dbo.getContentURL(177,1)

這給出了錯誤:

The name 'select --------------------' is not a valid identifier.

如何返回這個執行值?有人能幫幫我嗎?

我不能說我理解你想要做什麼……

問題是,就像你已經被告知的那樣,你不能在函式中使用動態 SQL。

使用儲存過程將解決您遇到的問題:(

我沒有嘗試找到另一個邏輯來檢索相同的數據,這是可能的,我只是將您的函式轉換為儲存過程)

CREATE PROC [dbo].[usp_getContentURL] 
(@VID INT, @accountID INT) 
AS 
DECLARE @cTable varchar(50) = '[CONTENT_CONNECT].[dbo].CONTENT_' + CONVERT(varchar(5),@accountID)
DECLARE @vTable varchar(50) = '[CONTENT_CONNECT].[dbo].VERSION_' + CONVERT(varchar(5),@accountID)
DECLARE @sql VARCHAR(max) =  '' 
SET @sql = ' 
DECLARE @CompanyID int
DECLARE @ProjectNumber int
DECLARE @ContentID int
DECLARE @VersionNumber int
DECLARE @FileName varchar(400)
select @VersionNumber=V.Number, @ContentID=V.ContentID, @ProjectNumber=P.Number, @FileName=C.Name, @CompanyID=P.CompanyID
from ' + @vTable + ' V
inner join' + @cTable + ' C on V.ContentID=C.ID
inner join Project P on C.ProjectID=P.ID 
where V.VID='+convert(varchar,@VID)+' 
select ''/''+Convert(varchar,@CompanyID)
+''/''+Convert(varchar,@ProjectNumber)
+''/''+Convert(varchar,@ContentID)
+''/''+Convert(varchar,@VersionNumber)
+''/''+@FileName'

EXEC (@sql)
GO

如果這不能滿足您的需求,請發布您正在嘗試做什麼。

祝你好運,

羅伊

引用自:https://dba.stackexchange.com/questions/24023