1
CREATE PROCEDURE dbo.usp_testing

AS
BEGIN
DECLARE @STATE INT,@TBLNAME sysname,@TrID VARCHAR(50),@FAMILYID VARCHAR(50),@SQL varchar(8000)

DECLARE cur CURSOR FOR
SELECT TrID,TableName 
FROM LogTable
WHERE Prefix='vid'
AND YEAR(DateTime)=YEAR(GETDATE())AND MONTH(DateTime)=MONTH(GETDATE())AND  DAY(DateTime)=DAY(GETDATE())

OPEN cur

FETCH NEXT FROM cur
INTO @TrID,@TBLNAME

IF(@TBLNAME='Student' OR @TBLNAME='Family' OR @TBLNAME='College')
BEGIN
**select @SQL='SELECT MemberID FROM'+' '+@TBLNAME+' '+'where TrId='+@TrID
select @FAMILYID=EXEC(@SQL)**

在这一行中,它给了我一个错误。

select @SQL='select @ID=(SELECT MemberID FROM'+' '+@TBLNAME+' '+'where TrId='+@TrID +')'

以及在这

exec(@sql) 

END

END
GO

我需要将 MemberID 放入变量 @ID

嗨,我做了一些更改,如下所述

ALTER PROCEDURE [dbo].[USP_TESTSP]

AS
BEGIN
DECLARE @SQL nvarchar(max),@TABLENAME sysname,@id nvarchar(max)
    SELECT @TABLENAME='student'
    select @SQL= 'select @id=MemberID FROM'+' '+@TABLENAME+' '+'where TrId=11091'
    exec sp_executesql @SQL,'@id nvarchar(max)output',@id=@id output
    --select exec (@SQL)

END

但得到一个错误:

过程需要类型为“ntext/nchar/nvarchar”的参数“@parameters”。

4

3 回答 3

1

考虑使用sp_executesql输出参数:

declare @SQL nvarchar(max)
set @SQL='SELECT @FAMILYID = MemberID FROM ' + @TBLNAME + ' where TrId=' + @TrID
exec sp_executesql @SQL, N'@FAMILYID int out', @FAMILYID = @FAMILYID out
于 2012-08-27T16:28:39.517 回答
1

sp_executesql声明动态查询的形式参数的参数应该'@id nvarchar(max)output'是 unicode 字符串。在 Transact-SQL 中,要指定字符串常量实际上是 unicode 字符串,您需要放在N左引号之前,如下所示:

N'@id nvarchar(max)output'

所以你USP_TESTSP应该看起来像这样:

ALTER PROCEDURE [dbo].[USP_TESTSP]

AS
BEGIN
DECLARE @SQL nvarchar(max),@TABLENAME sysname,@id nvarchar(max)
    SELECT @TABLENAME='student'
    select @SQL= 'select @id=MemberID FROM'+' '+@TABLENAME+' '+'where TrId=11091'
    exec sp_executesql @SQL,N'@id nvarchar(max)output',@id=@id output
    --select exec (@SQL)

END
于 2012-08-27T18:48:18.140 回答
0

这个对我有用:

select @SQL='SELECT @FAMILYID=MemberID FROM'+' '+@TBLNAME+' '+'where TrId='+@TrID
select EXEC(@SQL)
于 2012-08-27T16:36:27.900 回答