# L10 資料新增
###### tags: `SQL`
## 基本語法
針對資料
新增 **INSERT**
修改 **UPDATE**
刪除 **DELETE**
## 新增資料
==**Insert** 資料表(欄位)
**Values** 值==
可新增所有欄位,則只需寫資料表,欄位部分可省略
或新增部分欄位,則需標明欄位
**需特別注意其於欄位是否可允許NULL值**
ex.新增所有欄位
```sql=
USE Northwind
INSERT customers(customerid, companyname, contactname,
contacttitle,address, city, region, postalcode,
country, phone,fax)
VALUES ('PECOF', 'Pecos Coffee Company','Michael Dunn'
,'Owner', '1900 Oak Street', 'Vancouver', 'BC'
,'V3F 2K1', 'Canada', '(604) 555-3392'
,'(604) 555-7293')
GO
```
一樣寫法,新增所有欄位,則只需寫資料表,欄位部分可省略
```sql=
USE Northwind
INSERT customers
VALUES ('PECOF', 'Pecos Coffee Company','Michael Dunn'
,'Owner', '1900 Oak Street', 'Vancouver', 'BC'
,'V3F 2K1', 'Canada', '(604) 555-3392'
,'(604) 555-7293')
GO
```
ex. 新增部分欄位,沒給Values的欄位必須允許NULL或有識別規格
```sql=
USE Northwind
INSERT Shippers (Companyname)
VALUES ('Fitch & Mather')
GO
```
## 從其他資料表新增資料
==**Insert** 資料表(欄位)
**Select** 欄位
**From** 另一資料表==
ex.
```sql=
USE northwind
INSERT Customers([CustomerID],[CompanyName],
[ContactName],[ContactTitle],[Address],[City],
[Region],[PostalCode],[Country],[Phone])
SELECT substring (firstname, 1, 3)
+ substring (lastname, 1, 2)
,lastname, firstname, title, address, city
,region, postalcode, country, homephone
FROM Employees
GO
```
意義相同,也可以寫成
```sql=
USE northwind
INSERT Customers
SELECT substring (firstname, 1, 3)
+ substring (lastname, 1, 2)
,lastname, firstname, title, address, city
,region, postalcode, country, homephone,NULL
FROM Employees
GO
```
**Substring**('string',x,y)->在string這個字串中,從第x字元開始抓y個字元
## 建立新資料表FROM舊資料表
==**SELECT** 欄位
**INTO** (**#**)新建立資料表
**FROM** 舊資料表==
#新建立資料表->暫存資料表
暫存資料表**只存在於當下的Server Process ID**
關閉此連線(Server Process ID),暫存資料表也跟著消失
(不加# ,新建立資料表執行後會在資料庫出現)
ex. #暫存資料表
```sql=
USE Northwind
SELECT productname AS products
,unitprice AS price
,(unitprice * 1.1) AS tax
INTO #pricetable
FROM Products
GO
```
ex. 沒有#
```sql=
USE Northwind
SELECT productname AS products
,unitprice AS price
,(unitprice * 1.1) AS tax
INTO pricetable
FROM Products
GO
```
## 識別屬性 Identity Property
想像成一個流水號
一個資料表**只有一個**欄位可設定擁有識別屬性
此識別屬性的欄位資料型態必為 int, numeric, decimal
可用 @@Identity 查詢此連線上最新加入的流水號
:::info
開啟識別屬性->識別規格:是
識別值種子Ident_SEED:起始值
識別值增量Ident_INCR:遞增值
:::

管理識別屬性:
**SET** Identity_Insert 資料表名稱 **ON** 開啟
**SET** Identity_Insert 資料表名稱 **OFF** 關閉
ex. SET Identity_Insert **ON** 可以自己設定流水號
```sql=
USE Northwind
SET Identity_Insert [Shippers] ON
INSERT [dbo].[Shippers]([ShipperID],[CompanyName])
VALUES (100000,'TEST')
GO
```
結果為

ex.識別屬性以最大值跟著跳號
```sql=
USE Northwind
SET Identity_Insert [Shippers] OFF
INSERT [dbo].[Shippers]([CompanyName])
VALUES ('TEST')
GO
```
結果為

ex. [CompanyName] 不允許空值,會error
```sql=
USE Northwind
SET Identity_Insert [Shippers] OFF
INSERT [dbo].[Shippers]([Phone])
VALUES ('5555')
GO
```
結果為

ex.識別屬性依舊會記錄錯誤訊息,並跟著跳號
```sql=
USE Northwind
SET Identity_Insert [Shippers] OFF
INSERT [dbo].[Shippers]([CompanyName],[Phone])
VALUES ('55','5555')
GO
```
結果為

ex.查詢最新的流水號
```sql=
SELECT @@IDENTITY
FROM [dbo].[Shippers]
GO
```