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)
whereclause with Col4 or you want toselectcol4 when usertype is 'Admin'?