mysql的if 结果,可以将带有if语句的查询作为参数发送到MySql存储过程并返回其结果...

helo all,

i am migrating my db from mssql to mysql. i have queries like this in my applications front end (in C#):

if exists(select * from table1) then

select * from table1;

else

select * from table2

end if;

now this cant be passed as command text for MySqlCommand. tutorials all over net say that if..else can be embedded only in stored procs & functions in mysql. but even then the condition part for if is not working properly. can anyone suggest a solution??

--AR

解决方案AR wrote:but even then the condition part for if is not working properly

You are writing the if statement improperly for SQL syntax. Instead, you want:

IF EXISTS (SELECT 1 FROM Table1)

BEGIN

SELECT * FROM Table1

END

ELSE

BEGIN

SELECT * FROM Table2

END

Put that into a stored procedure. If you want everything to be in a single ad-hoc query (without a stored procedure), you could do something like this:

SELECT

Table1.Column1 AS FirstColumn,

Table1.Column9 AS SecondColumn

FROM Table1

WHERE EXISTS

(

SELECT 1 FROM Table1

)

UNION

SELECT

Table2.Column2 AS FirstColumn,

Table2.ColumnR as SecondColumn

FROM Table2

WHERE NOT EXISTS

(

SELECT 1 FROM Table1

)

At least, that''s how it works on Microsoft SQL Server. Might be different for MySQL.

In most cases, it would be bad practice, but you might be able to use "prepared statements" to do this. The idea is that you''d create a bit of SQL in a string in C# that acts like a predicate (returns true or false). Then, you''d pass that SQL string to be executed by a stored procedure which knows what to return if the statement is true and what to return if the statement is false (but it doesn''t know in advance what that statement is). Read more about prepared statements here. Another name for this is "dynamic SQL", but the methods to use them differ between MSSQL and MySQL.

To add to my previous answer, you could have a stored procedure and pass 4 strings to it. Two of them would be the if statements (or only one if statement if the second if statement is just an else), and two would be statements that return one of two possible results.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值