简体   繁体   English

临时表中的IF语句

[英]IF statement from a temp table

I have a temp table with some columns containing numbers. 我有一个临时表,其中某些列包含数字。 I want to use the columns in the temp table and compare them WITH an IF statement. 我想使用临时表中的列,并将它们与IF语句进行比较。

...


INSERT INTO #tmp
EXEC [p_GetComplete] @Car_ID

IF Col1 + Col2 = Col3
BEGIN
 PRINT 'OK'
END
ELSE 
BEGIN
 PRINT 'NO'
END

...

SQL Is made to operate on SET, so avoid CASE WHEN and IF as long as you can: 使SQL在SET上运行,因此,只要可以,请避免使用CASE WHEN和IF:

You can do it this way (recommended): 您可以通过以下方式做到这一点(推荐):

SELECT 'Ok' FROM #tmp WHERE Col1+Col2=Col3
UNION ALL
SELECT 'NO' FROM #tmp WHERE NOT (Col1+Col2=Col3)

or this way: 或者这样:

SELECT CASE WHEN Col1+Col2=Col3 THEN 'Ok' ELSE NO FROM #tmp WHERE 

You can use case statement, when wanting to insert different value to #tmp table, according to some conditions. 根据某些条件,当要将不同的值插入#tmp表时,可以使用case语句。

Such as on: 如:

SQL Server: CASE WHEN OR THEN ELSE END => the OR is not supported SQL Server:CASE WHEN OR THEN ELSE END =>不支持OR

If you want searching every record, and do some printing, there is good example on: http://technet.microsoft.com/en-us/library/ms180152.aspx 如果要搜索每条记录并进行一些打印,请参见以下示例: http : //technet.microsoft.com/zh-cn/library/ms180152.aspx

Good luck!!! 祝好运!!!

Presumably, the exec is only returning one row and the only way you can capture the data is into a table. 大概是, exec程序只返回一行,而捕获数据的唯一方法是放入表中。 You can rewrite the stored procedure to have proper OUTPUT parameters, but let's assume that's not possible. 您可以重写存储过程以使其具有正确的OUTPUT参数,但让我们假设这是不可能的。

You can do what you want as: 您可以按照自己的意愿做:

INSERT INTO #tmp
EXEC [p_GetComplete] @Car_ID

IF exists(select * from #temp where Col1 + Col2 = Col3)
BEGIN
 PRINT 'OK';
END
ELSE 
BEGIN
 PRINT 'NO';
END;

That is, if a row exists where the condition is true, then print 'OK' . 也就是说,如果存在满足条件的行,则打印'OK'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM