SELECT查出多行 INTO 單行上會把第一行賦值到單行上

--關於SELECT INTO 一直以來的錯誤認知: --若是查出來多條數據,不只會拋出異常,並且會把第一行數據賦值上去,直接上例子sql

CREATE TABLE  SELECT_INTO_TEST (T_ID NUMBER,T_NAME VARCHAR2(10),T_LOCATION VARCHAR2(50));

INSERT  INTO SELECT_INTO_TEST 
SELECT 1,'RICK','AMERICAN'  FROM DUAL
UNION ALL
SELECT 2,'SON','AMERICAN' FROM DUAL;
COMMIT;
SELECT * FROM  SELECT_INTO_TEST;

查詢出結果爲:code

輸入圖片說明

--例子一:查出多條數據會自動填充第一行,因此輸出爲: ** V_ID=1V_NAME=RICKV_LOACTION=AMERICAN**圖片

DECLARE 
V_ID NUMBER;
V_NAME VARCHAR2(10);
V_LOCATION VARCHAR2(50);
BEGIN
BEGIN
  SELECT T_ID,T_NAME,T_LOCATION 
  INTO V_ID,V_NAME,V_LOCATION FROM SELECT_INTO_TEST;
  EXCEPTION WHEN OTHERS THEN
  NULL;
END;
 DBMS_OUTPUT.PUT_LINE('V_ID='||V_ID||'V_NAME='||V_NAME||'V_LOACTION='||V_LOCATION);
END;
--這樣寫才比較正確 :若是查出多條數據,拋出異常,清空表數據
DECLARE 
V_ID NUMBER;
V_NAME VARCHAR2(10);
V_LOCATION VARCHAR2(50);
BEGIN
BEGIN
  SELECT T_ID,T_NAME,T_LOCATION 
  INTO V_ID,V_NAME,V_LOCATION FROM SELECT_INTO_TEST;
  EXCEPTION WHEN OTHERS THEN
  V_ID := NULL;
  V_NAME := NULL;
  V_LOCATION := NULL;
END;
 DBMS_OUTPUT.PUT_LINE('V_ID='||V_ID||'V_NAME='||V_NAME||'V_LOACTION='||V_LOCATION);
END;

總結: 以前一直認爲若是查出多條 INTO 到單行上,會直接報錯,賦值爲空,這一直是一個認知錯誤,若是多條INTO到單行,會把第一行數據賦值上。 --因此須要再 EXCEPTION 中清空數據。it

相關文章
相關標籤/搜索