1

Given a table rules

rule_id = 1
rule_condition = 'size > 15'

how can I run a query like this

SELECT * FROM rawdata where (Select rule_condition FROM rules WHERE rule_id=1)

Is the only way to do it a stored procedure like this: mysql - query inside a query

14
  • What records are you wanting? The exmple just returns the same result as the nested query.. Commented Mar 9, 2011 at 15:00
  • Your query has table rawdata, which isn't joining to the subquery. Try adding a join condition, i.e. where rawdata.column = (select rule_condition...) Commented Mar 9, 2011 at 15:03
  • Do you want the outer SQL SELECT * FROM rawdata to be executed with a fully dynamic WHERE clause? In your example you want the query to return the results of SELECT * FROM rawdata WHERE Size > 15 ? Commented Mar 9, 2011 at 15:06
  • Lets backup for a sec.. Essentially you want a select statment to return a record set for rule_id = 1 and rule_condition = 'size > 15' correct? What type of column is rule_condition (what type of data is stored there) Commented Mar 9, 2011 at 15:14
  • @Carpe: in the rawdata table there would be records like size = 10 and size = 17 of these I want only the ones matching the condition, so in Commented Mar 9, 2011 at 15:15

2 Answers 2

2

This is essential reading for you before starting with dynamic SQL

For SQL Server you would use something like...

DECLARE @dynamicsql NVARCHAR(1000)

SELECT @dynamicsql =N'SELECT * FROM rawdata where ' + rule_condition 
FROM rules 
WHERE rule_id=1

IF(@@ROWCOUNT = 1)
   EXEC(@dynamicsql)

Hopefully you are not planning on allowing users to enter arbitrary rule_condition s as they could execute any arbitrary statements against your SQL Server.

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

1 Comment

Thanks, I will try as soon as I have access to my server, the rule_condition won't be public
2
declare whereClause VarChar(128);
BEGIN 

Select rule_condition into whereClause FROM rules WHERE rule_id=1
SET @s = CONCAT('SELECT * FROM rawdata where ', whereClause;) 
PREPARE stmt1 FROM @s; 
EXECUTE stmt1; 
DEALLOCATE PREPARE stmt1; 

END

This should get you close.

Note this will only work if the first select that selects a string into whereClause is a single record.

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.