在存储过程中加入Dynamic Query

时间:2015-09-03 09:27:01

标签: sql-server join stored-procedures

我想加入第一个查询。

public class Manager
{
    BasicErrorHandler _errorHandler;

    public Manager()
    {
        _errorHandler = new BasicErrorHandler();
    }

    public void MethodA()
    {
        _errorHandler.Do(() => {
            //Does Something    
        });
    }

    public void MethodB()
    {
        _errorHandler.Do(() => {
            //Does Something Else
        });
    }
}

想要以单行显示。

我的输出是,

    select UserName from UserRegistration where UserID = @UserID


     SET @sqlText = N'SELECT isnull(SUM(isnull(['+REPLACE(@columns,',','],0)),
SUM(isnull([') + '],0)), 0)' +' FROM dbo.timesheet
 where month ='''+ @strMonth+''' and [year] =' +
 Cast(@year1 AS VARCHAR(max))+  'and [Task ID] 
in(select TaskID from ManageTasks where TeamMemberUserID ='+ 
 Cast(@UserID AS VARCHAR(max)) +')'

我想显示为,

    Username 
-------------------- 
    myName
--------------------

    (No column Name)
--------------------
       49
-------------------

2 个答案:

答案 0 :(得分:0)

只需将用户名添加到动态sql字符串中:

DECLARE @UserName NVARCHAR(50);
select @UserName = UserName from UserRegistration where UserID = @UserID;

SET @sqlText = N'SELECT ''' + @UserName + ''' AS UserName
                        , isnull(SUM(isnull(['+REPLACE(@columns,',','],0))
                        , SUM(isnull([') + '],0)), 0)' +'
                FROM dbo.timesheet
                WHERE   month ='''+ @strMonth+''' 
                        and [year] =' + Cast(@year1 AS VARCHAR(max)) + '
                        and [Task ID] in (select TaskID from ManageTasks where TeamMemberUserID =' + Cast(@UserID AS VARCHAR(max)) +');'

答案 1 :(得分:0)

尝试下面

SET @sqlText = N'SELECT ur.UserName,
isnull(SUM(isnull(['+REPLACE(@columns,',','],0)),
SUM(isnull([') + '],0)), 0)' +' FROM dbo.timesheet i
inner join ManageTasks mt on i.[Task ID] =  mt.TaskId
inner join UserRegistration ur on mt.TeamMemberUserID  = ur.Username
 where month ='''+ @strMonth+''' and [year] =' +
 Cast(@year1 AS VARCHAR(max))+  'ur.UserName ='+ 
 Cast(@UserID AS VARCHAR(max)) +') group by ur.UserName'

如果您需要更多帮助,请告诉我