选择Top 1字段并分配给本地变量,其中数据库名称是动态的

时间:2017-07-21 15:56:22

标签: sql sql-server

在sql server下面执行时,我无法在代码中传递@AKM参数,但是我能够重现在简单查询中执行的相同操作。但是我能够为id传递变量,因为它是一个int类型,但@akm是charecter

CREATE PROCEDURE [dbo].[sp_akm_test]
    @AKM NVARCHAR(128), 
    @Anlsid Int
    AS 
    DECLARE @Sql1 NVARCHAR(MAX);
    DECLARE @type NVARCHAR(MAX);
    BEGIN
    SELECT TOP 1 @type= sample_type FROM ' + @RDM +'.dbo.analysis where ID= '@id
        PRINT(@type)
            IF (@type = 8017)
            BEGIN 
            SET @Sql1 = N'select sample_n FROM'+ QUOTENAME(@AKM) +'..sample'
            END
            ELSE
            Begin
            SET @Sql1 = N'select sampleid FROM'+ QUOTENAME(@AKM) +'..sample'
            END
    EXECUTE sp_executesql @Sql1
    END

1 个答案:

答案 0 :(得分:0)

我想你需要这样的东西

declare @RDM sysname = ???? -- pass the db name, missing in your code
declare @sql nvarchar(4000)= '',@type int

set @sql = '
SELECT TOP 1 @type= sample_type FROM ' + quotename(@RDM) +'.dbo.rdm_analysis where ID=110'

exec sp_executesql @sql,N'@type int output',@type = @type output

SET @Sql1 = '
select case when @type = 8017 then sample_n else sampleid end 
FROM'+ QUOTENAME(@AKM) +'..sample'

exec sp_executesql @sql1,N'@type int',@type