0

I have a dynamic SQL query which selects table name based on user type. Here both Admin & User tables have similar columns but Admin table have one additional column 'Col4'.

Now I need to pass this additional column value if the selected table is AdminTable else I need to pass default hard-coded value in below dynamic sql query.

Is there any SQL keyword or any simple way to achieve this functionality?

IF @UserType = 'Admin'                                                                                   
 SET @TableName = 'AdminTable'   
ELSE IF @UserType = 'User'                        
 SET @TableName = 'UserTable' 

SET @SqlQuery = 'SELECT Col1,Col2,Col3 FROM '+@TableName+' WITH(NOLOCK)'
EXEC (@SqlQuery) 

Answer: Below one works for me.

SET @SqlQuery = 'SELECT Col1,Col2,Col3,Case When COL_LENGTH(''@TableName'', ''Col4'') IS NOT NULL THEN Col4 Else 0 END as AdminRole FROM '+@TableName+' WITH(NOLOCK)'
EXEC (@SqlQuery) 
2
  • What do you mean by " pass this additional column value if the selected table is AdminTable". Do you want to have a where clause with Col4 or you want to select col4 when usertype is 'Admin'? Commented Jul 12, 2018 at 5:44
  • @AB_87 I want to select col4 when usertype is Admin otherwise I need to pass some default value in the select list. Commented Jul 12, 2018 at 5:48

2 Answers 2

2
IF @UserType = 'Admin'                                                                                   
 SET @SqlQuery = 'SELECT Col1,Col2,Col3,Col4 FROM '+@UserType+'Table'+' WITH(NOLOCK)'
ELSE IF @UserType = 'User'                        
 SET @SqlQuery = 'SELECT Col1,Col2,Col3 FROM ' +@UserType+'Table'+' WITH(NOLOCK)' 

EXEC (@SqlQuery) 

Guess you have to do it this way as an additional column is involved.

Sign up to request clarification or add additional context in comments.

Comments

1

You can simply change your query text based on condition.

DECLARE @DefaultValue INT = 10
IF @UserType = 'Admin'
    SET @SqlQuery = 'SELECT Col1,Col2,Col3, Col4 FROM AdminTable WITH(NOLOCK)' ;    
ELSE IF @UserType = 'User'
    SET @SqlQuery = 'SELECT Col1,Col2,Col3, ' + CAST(@DefaultValue AS VARCHAR(10)) + ' as C4 ' + 'FROM UserTable WITH(NOLOCK)';


EXEC ( @SqlQuery );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.