1
我需要船長的幫助,顯然我猜。我試圖從表格中插入數據到一個可變的表格中。好吧,這很容易右鍵加入多鍵無效的鍵
我需要插入我們今天得到的數據和我們在10天前得到的數據。 where子句可以aford它,日的還好
什麼對我來說是難是插入今天的數據,只有當它不存在於數據顯示在10天前
我用的是表的爲例([數據表):
Date Purchase Line_Purchase
---------------------------------------------------------------------------
2017-04-29 0000002 01
2017-04-29 0000002 02
2017-04-29 0000003 01
2017-04-29 0000003 02
2017-04-29 0000003 03
2017-04-29 0000004 01
2017-04-29 0000005 01
2017-04-19 0000001 01
2017-04-19 0000001 02
2017-04-19 0000001 03
2017-04-19 0000002 01
2017-04-19 0000002 02
我所需的表temptable
:
Input_date Purchase Line_Purchase
-------------------------------------------------------------------------
2017-04-19 0000001 01
2017-04-19 0000001 02
2017-04-19 0000001 03
2017-04-19 0000002 01
2017-04-19 0000002 02
2017-04-29 0000003 01
2017-04-29 0000003 02
2017-04-29 0000003 03
2017-04-29 0000004 01
2017-04-29 0000005 01
有什麼要求可以在SQL中可以改變這種狀況?
我試過這樣
INSERT INTO #TEMPTABLE
(Input_date ,Purchase ,Line_Purchase)
SELECT
table.Date
,table.Purchase
,table.Line_Purchase
FROM
datatable table
WHERE
convert(date, table.Date) = convert(date, GETDATE() - 10)
INSERT INTO #TEMPTABLE
(Input_date ,Purchase ,Line_Purchase)
SELECT
table.Date
,table.Purchase
,table.Line_Purchase
FROM
datatable table
RIGHT JOIN #TEMPTABLE temp
on table.Purchase = temp.Purchase and table.Line_Purchase = temp.Line_Purchase
WHERE
convert(date, table.Date) = convert(date, GETDATE())
AND (temp.Purchase is null AND temp.Line_Purchase is null)
在此先感謝
從T作爲我 我不明白,選擇1爲什麼選擇1,而不是選擇* –
我用'選擇1'出的習慣。 'exists()'和'not exists()'不返回行,所以你可以使用'select null','select 1','select *',甚至'select 1/0'。 基於這篇文章[EXISTS子查詢:SELECT 1與SELECT * - Conor Cunningham](http://www.sqlskills.com/blogs/conor/exists-subqueries-select-1-vs-select/)使用'select 1'將避免在查詢編譯期間檢查該表的任何不需要的元數據。 [EXISTS子查詢:選擇1與選擇* - Martin Smith](https://stackoverflow.com/a/6140367/2333499)運行的測試顯示實際性能沒有差異。 – SqlZim
謝謝你的解釋 –