1

I have a field that stores value like >=99.35 (storing goals in table) and lets say the actual data value is 78. I then need to compare if goal met or not. How can I accomplish this?

I tried to put that in a @sql variable which will say like:

Select case when 78>=99.35 then 1 else 0 end

but how can I execute this @sql to get the value 1 or 0 in a field of a table?

Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
  • take a look at EXEC sp_executesql @sql – Mark Aug 13 '15 at 14:10
  • What you've written is [dynamic SQL](https://msdn.microsoft.com/en-us/library/ms188001.aspx). The MSFT article shows how to execute such a statement. – xQbert Aug 13 '15 at 14:13

3 Answers3

0
DECLARE @sql VARCHAR(1000);
DECLARE @Result INT;

SET @Result = 78;
SET @sql = 'SELECT CASE WHEN ' + @Result + ' >=99.35 THEN 1 ELSE 0 END'

EXEC sp_executesql @sql 

Using sp_executesql is more likely to cache the query plan if you are going to be repeatedly calling this SQL statement.

Neil Knight
  • 47,437
  • 25
  • 129
  • 188
  • Yes, this runs fine but I need to update another field with the value returned from @sql something like - update x set field = exec (@sql) – user4946275 Aug 13 '15 at 14:39
  • @user4946275: See [this question](http://stackoverflow.com/questions/803211/how-to-get-sp-executesql-result-into-a-variable). – Joe Farrell Aug 13 '15 at 14:48
0
DECLARE @ActualValue INT = 100

DECLARE @SQLQuery nVARCHAR(MAX) = ''

SET @SQLQuery = ( SELECT 'SELECT CASE WHEN '+CONVERT(VARCHAR,@ActualValue)+ YourColumn+ 'THEN 1 ELSE 0 END AS ResultValue'  FROM YourTable )


EXECUTE sp_executesql  @SQLQuery
mindbdev
  • 404
  • 3
  • 8
0

A solution using sp_executesql as described in the other answers will work fine, but if you're going to be executing the contents of a table as part of a dynamic SQL statement, then you need to be very careful about what can be stored in that field. Do the goals you're storing always consist of a single operator and a target value? If so, it wouldn't be hard to store the two separately and process them with a static query. Something like:

declare @SampleData table
(
    [ActualValue] decimal(11, 2), 
    [Operator] varchar(2), 
    [ReferenceValue] decimal(11, 2)
);
insert @SampleData values
    (100, '>=', 98.25),
    (100, '<=', 98.25),
    (100, 'G', 98.25);

select
    [ActualValue],
    [Operator],
    [ReferenceValue],
    [GoalMet] = case [Operator]
        when '>=' then case when [ActualValue] >= [ReferenceValue] then 1 else 0 end
        when '<=' then case when [ActualValue] <= [ReferenceValue] then 1 else 0 end
        /*...other operators here if needed...*/
        else null
    end
from
    @SampleData;

This is a bit more verbose but perhaps a bit safer as well. Maybe it's usable for your general case and maybe it's not; I just thought I'd throw it out there as an alternative.

Joe Farrell
  • 3,502
  • 1
  • 15
  • 25