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
谢谢你的解释 –