0

I want to run the following SELECT query:

DECLARE @ColumnName nvarchar(50)
SET @ColumnName = 'AlarmID' -- actually these are calculated 
                            -- by another SELECT but this isn't relevant
SELECT MIN(@ColumnName) FROM INSERTED

This doesn't work, it returns the value of @ColumnName instead of the actual data. How can I make this work?

I cannot put the SELECT into a string and run it with sp_executesql because I will lose access to the INSERTED table (this is running in a trigger).

5
  • what is the value returned by @ColumnName and your expected result? Commented Feb 25, 2013 at 13:49
  • In the above example, the value the select returns is 'AlarmID', I was expecting an int as the AlarmID column in the INSERTED table is an int. Commented Feb 25, 2013 at 13:51
  • maybe you can add sample records with desired result and the unrelevant sql query. Commented Feb 25, 2013 at 13:51
  • Have you tried this: stackoverflow.com/questions/10092869/… Commented Feb 25, 2013 at 13:55
  • Also see this post: stackoverflow.com/questions/2942082/… Commented Feb 25, 2013 at 13:56

3 Answers 3

1
EXEC('SELECT MIN(' + @ColumnName + ') FROM INSERTED')

Derived from the link smoore provided.

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

Comments

0

Use this if you want the minimum as a variable:

SELECT @columnName = MIN(@ColumnName) FROM YourTable

Comments

0

You can't really do that. Your best bet, depending on number of possible values of @ColumnName, is to dynamically set the field value with a case statement, or selectively run the right query using an IF statement:

SELECT CASE @ColumnName WHEN 'AlarmID' THEN MIN(AlarmID) WHEN 'AnotherField' THEN
MIN(AnotherField) END AS MinimumValue FROM INSERTED

OR

IF @ColumnName = 'AlarmID'
  SELECT MIN(AlarmID) FROM INSERTED
ELSE
  ....

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.