首先,你需要創建表將保留timestamp
,id
,length
和dataid
:
CREATE TABLE packet_data (
pd_timestamp datetime NOT NULL,
id int NOT NULL,
[length] int NOT NULL,
dataid int IDENTITY (1,1) NOT NULL,
CONSTRAINT PK_packet_data PRIMARY KEY CLUSTERED (dataid),
)
然後表,將持有的數據部分:
CREATE TABLE main_data (
dataid int NOT NULL,
data_value nvarchar(10) NOT NULL
CONSTRAINT PK_main_data PRIMARY KEY CLUSTERED (dataid, data_value)
)
然後加入FK:
ALTER TABLE main_data ADD
CONSTRAINT FK_main_data_packet_data FOREIGN KEY (dataid)
REFERENCES packet_data (dataid)
ON DELETE CASCADE
ON UPDATE CASCADE
所以你會得到一個一對多的關係,通過dataid
字段來存儲你的數據標準化。
然後用SP來加載數據:
CREATE PROCEDURE add_data
@string nvarchar(max)
AS
BEGIN
DECLARE @id int,
@length int,
@data_array nvarchar(max),@xml xml,
@n int = 0, @i int = 0, @s int = 3,
@current datetime = GETDATE()
SELECT @id = CAST(LEFT(@string,2) as int),
@length = CAST(SUBSTRING(@string,3,2) as int),
@data_array = RIGHT(@string,LEN(@string)-4)
SELECT @n = LEN(@data_array)/2 - 1
WHILE @n > @i
BEGIN
SELECT @data_array = STUFF(@data_array,@s,0,'-')
SET @[email protected]+1
SET @[email protected]+3
END
SELECT @xml = CAST('<a>'+REPLACE(@data_array,'-','</a><a>') + '</a>' as xml)
INSERT INTO packet_data ([pd_timestamp], [id], [length])
VALUES (@current, @id, @length)
INSERT INTO [dbo].[main_data]
SELECT @@IDENTITY,
t.v.value('.','nvarchar(10)')
FROM @xml.nodes('/a') as t(v)
END
如果執行你的SP,如:
EXEC add_data N'4144010203040506'
你會得到這個表packet_data
:
pd_timestamp id length dataid
2016-06-18 18:24:28.153 41 44 1
在表main_data
:
dataid data_value
1 01
1 02
1 03
1 04
1 05
1 06
你的問題還不清楚,你問如何存儲數據或如何創建一個程序? –
SQL Server *不具有「數組」數據類型,並且您*不應該*在單列中存儲多個數據塊(即**違反了關係設計的基本第一範式).... –