SQLTeam.com | Weblogs | Forums

How to execute SQL command baed on output of another SQL command


#1

HI,

I am using mssql database. Please help me to execute the sql queries based on output of another sql query as follows.
I have one query like 'select productcode from test' . It lists all the product codes.
Based on above query output, If any one of productcode value from above query is "aaaa" then execute sql query1 otherwise execute sql query2.

Please help me.

-regards
Nagendra Rednam


#2
IF EXISTS
(
	SELECT * FROM test
	WHERE productcode = 'aaaa'
)
BEGIN
	-- Code for query1 here
END
ELSE
BEGIN
	-- Code for query2 here
END

#3

It's very helpful for me. Thank You very much.

-regards
Nagendra


#4

HI,
Need some more help on below snippet.

IF EXISTS
(
SELECT * FROM test
WHERE productcode = 'aaaa'
)

If sub string of product code is 'aaaa' (not exact match) then i want to execute the query1 else query2.

Please help me.

-thanks
Nagendra


#5

If the product code starts with 'aaaa', use

WHERE productcode like 'aaaa%'

If 'aaaa' is somewhere embedded in the productcode, use

WHERE productcode like '%aaaa%'

You can use the second form even if the product code starts with 'aaaa', but the first form is likely to be more efficient if you can be certain that you want the productcodes that start with 'aaaa' rather than embedded somewhere in the productcode.