0

Please help me I am trying to do this:

 DECLARE @QUERY NVARCHAR(500) = ' declare @col as nvarchar(50) = ''RoleID''
  select @col from tblRole '
  EXEC sp_executesql @QUERY

Here RoleID is a column name in tblRole but I am getting result like this:

RoleID 
RoleID 
RoleID 
RoleID 
RoleID 
RoleID 
RoleID

How to read proper data from sql table in this way?

5
  • You cannot "parametrize" table or column names. If you want to do this, you have to use dynamic SQL with all its benefits (and drawbacks) Commented Jan 8, 2015 at 10:30
  • why you want to do so? Commented Jan 8, 2015 at 10:35
  • @marc_s I am doing this in store procedure with EXEC sp_executesql. But I am stuck at this point Commented Jan 8, 2015 at 10:52
  • @AngularDev I am working on a Pivot report. In this report before returning result to project, I have to modify its values on some conditions. That is why I need to do in this way. Commented Jan 8, 2015 at 10:54
  • Please help me I am still not able to do it. Commented Jan 8, 2015 at 12:57

1 Answer 1

0

If you want to select the RoleID column then your select should be...

SELECT RoleID FROM tblRole

If you want to select a value = 'RoleID' then...

SELECT * FROM tblRole where RoleID = @col

IF on the other hand you want to select a column by dynamically passing it as a variable then click on the link below.

Click here

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

2 Comments

Yes @Andrew N I need to select column by passing it dynamically. this link looks relevant. I am working on it
Please help me I am still not able to do it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.