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'。
答案 0 :(得分: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
答案 1 :(得分:1)
声明动态查询的形式参数sp_executesql
的{{1}}参数应该是unicode字符串。在Transact-SQL中,要指定字符串常量实际上是unicode字符串,您需要将'@id nvarchar(max)output'
放在开始引号之前,如下所示:
N
所以你的N'@id nvarchar(max)output'
应该是这样的:
USP_TESTSP
答案 2 :(得分:0)
它对我有用:
select @SQL='SELECT @FAMILYID=MemberID FROM'+' '+@TBLNAME+' '+'where TrId='+@TrID
select EXEC(@SQL)