Home Backend Development PHP Tutorial Solution to Sqlserver's slow insertion speed or data loss of large amounts of data

Solution to Sqlserver's slow insertion speed or data loss of large amounts of data

Jan 13, 2017 pm 03:43 PM

My device inserts 2,000 pieces of data into the database every second, and the two devices total 4,000. When inserting directly using the insert statement in the program, the two devices can insert a total of about 2,800 pieces at the same time, and the data is lost. There are about 1,200 items. After testing many methods, two solutions with obvious effects were sorted out:

Method 1: Use Sql Server function:

1. Combine the data into strings , use the function to insert data into the memory table, and then copy the memory table data to the table to be inserted.

2. Change the format of the combined characters: '111|222|333|456,7894,7458|0|1|2014-01-01 12:15:16;1111|2222|3333|456 ,7894,7458|0|1|2014-01-01 12:15:16', Each row of data is separated by ";", and each field is separated by "|".

3. Write function:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

CREATE FUNCTION [dbo].[fun_funcname](@str VARCHAR(max),@splitchar CHAR(1),@splitchar2 CHAR(1))

--定义返回表 

RETURNS @t TABLE(MaxValue float,Phase int,SlopeValue float,Data varchar(600),Alarm int,AlmLev int,GpsTime datetime,UpdateTime datetime) AS 

/*    

author:hejun li  

create date:2014-06-09  

*/  

BEGIN 

DECLARE @substr VARCHAR(max),@substr2 VARCHAR(max)

--申明单个接收值

declare @MaxValue float,@Phase int,@SlopeValue float,@Data varchar(8000),@Alarm int,@AlmLev int,@GpsTime datetime

SET @substr=@str  

DECLARE @i INT,@j INT,@ii INT,@jj INT,@ijj1 int,@ijj2 int,@m int,@mm int

SET @j=LEN(REPLACE(@str,@splitchar,REPLICATE(@splitchar,2)))-LEN(@str)--获取分割符个数  

IF @j=0  

  BEGIN 

   --INSERT INTO @t VALUES (@substr,1) --没有分割符则插入整个字串 

   set @substr2=@substr;

   set @ii=0

   SET @jj=LEN(REPLACE(@substr2,@splitchar2,REPLICATE(@splitchar2,2)))-LEN(@substr2)--获取分割符个数

     WHILE @ii<=@jj

        BEGIN

          if(@ii<@jj)

            begin

              SET @mm=CHARINDEX(@splitchar2,@substr2)-1 --获取分割符的前一位置

              if(@ii=0)

                set @MaxValue=cast(LEFT(@substr2,@mm) as float)

              else if(@ii=1)

                set @Phase=cast(LEFT(@substr2,@mm) as int)

              else if(@ii=2)

                set @SlopeValue=cast(LEFT(@substr2,@mm) as float)

              else if(@ii=3)

                set @Data=cast(LEFT(@substr2,@mm) as varchar)

              else if(@ii=4)

                set @Alarm=cast(LEFT(@substr2,@mm) as int)

              else if(@ii=5)

                set @AlmLev=cast(LEFT(@substr2,@mm) as int)

              else if(@ii=6)

                INSERT INTO @t VALUES(@MaxValue,@Phase,@SlopeValue,&#39;&#39;+@Data+&#39;&#39;,@Alarm,@AlmLev,cast(@substr2 as datetime),GETDATE())

              SET @substr2=RIGHT(@substr2,LEN(@substr2)-(@mm+1)) --去除已获取的分割串,得到还需要继续分割的字符串

            end

          else

            BEGIN

              --当循环到最后一个值时将数据插入表

              INSERT INTO @t VALUES(@MaxValue,@Phase,@SlopeValue,&#39;&#39;+@Data+&#39;&#39;,@Alarm,@AlmLev,cast(@substr2 as datetime),GETDATE())

            END

        --END

        SET @ii=@ii+1

      END

  END 

ELSE 

BEGIN 

 SET @i=0  

 WHILE @i<=@j  

 BEGIN 

  IF(@i<@j)  

  BEGIN 

  SET @m=CHARINDEX(@splitchar,@substr)-1 --获取分割符的前一位置

  --INSERT INTO @t VALUES(LEFT(@substr,@m),@i+1)

  -----二次循环开始

  --1.线获取要二次截取的字串

  set @substr2=(LEFT(@substr,@m));

  --2.初始化二次截取的起始位置

  set @ii=0

  --3.获取分隔符个数

  SET @jj=LEN(REPLACE(@substr2,@splitchar2,REPLICATE(@splitchar2,2)))-LEN(@substr2)--获取分割符个数

  WHILE @ii<=@jj

    BEGIN

      if(@ii<@jj)

        begin

          SET @mm=CHARINDEX(@splitchar2,@substr2)-1 --获取分割符的前一位置

          if(@ii=0)

            set @MaxValue=cast(LEFT(@substr2,@mm) as float)

          else if(@ii=1)

            set @Phase=cast(LEFT(@substr2,@mm) as int)

          else if(@ii=2)

            set @SlopeValue=cast(LEFT(@substr2,@mm) as float)

          else if(@ii=3)

            set @Data=cast(LEFT(@substr2,@mm) as varchar)

          else if(@ii=4)

            set @Alarm=cast(LEFT(@substr2,@mm) as int)

          else if(@ii=5)

            set @AlmLev=cast(LEFT(@substr2,@mm) as int)

          else if(@ii=6)

            INSERT INTO @t VALUES(@MaxValue,@Phase,@SlopeValue,&#39;&#39;+@Data+&#39;&#39;,@Alarm,@AlmLev,cast(@substr2 as datetime),GETDATE())

          SET @substr2=RIGHT(@substr2,LEN(@substr2)-(@mm+1)) --去除已获取的分割串,得到还需要继续分割的字符串

        end

      else

        BEGIN

          --当循环到最后一个值时将数据插入表

          INSERT INTO @t VALUES(@MaxValue,@Phase,@SlopeValue,&#39;&#39;+@Data+&#39;&#39;,@Alarm,@AlmLev,cast(@substr2 as datetime),GETDATE())

        END

    --END

    SET @ii=@ii+1

  END

  -----二次循环结束

  SET @substr=RIGHT(@substr,LEN(@substr)-(@m+1)) --去除已获取的分割串,得到还需要继续分割的字符串  

  END 

 ELSE 

  BEGIN

  --INSERT INTO @t VALUES(@substr,@i+1)--对最后一个被分割的串进行单独处理

  -----二次循环开始

  --1.线获取要二次截取的字串

  set @substr2=@substr;

  --2.初始化二次截取的起始位置

  set @ii=0

  --3.获取分隔符个数

  SET @jj=LEN(REPLACE(@substr2,@splitchar2,REPLICATE(@splitchar2,2)))-LEN(@substr2)--获取分割符个数

  WHILE @ii<=@jj

    BEGIN

      if(@ii<@jj)

        begin

          SET @mm=CHARINDEX(@splitchar2,@substr2)-1 --获取分割符的前一位置

          if(@ii=0)

            set @MaxValue=cast(LEFT(@substr2,@mm) as float)

          else if(@ii=1)

            set @Phase=cast(LEFT(@substr2,@mm) as int)

          else if(@ii=2)

            set @SlopeValue=cast(LEFT(@substr2,@mm) as float)

          else if(@ii=3)

            set @Data=cast(LEFT(@substr2,@mm) as varchar)

          else if(@ii=4)

            set @Alarm=cast(LEFT(@substr2,@mm) as int)

          else if(@ii=5)

            set @AlmLev=cast(LEFT(@substr2,@mm) as int)

          else if(@ii=6)

            INSERT INTO @t VALUES(@MaxValue,@Phase,@SlopeValue,&#39;&#39;+@Data+&#39;&#39;,@Alarm,@AlmLev,cast(@substr2 as datetime),GETDATE())

          SET @substr2=RIGHT(@substr2,LEN(@substr2)-(@mm+1)) --去除已获取的分割串,得到还需要继续分割的字符串

        end

      else

        BEGIN

          --当循环到最后一个值时将数据插入表

          INSERT INTO @t VALUES(@MaxValue,@Phase,@SlopeValue,&#39;&#39;+@Data+&#39;&#39;,@Alarm,@AlmLev,cast(@substr2 as datetime),GETDATE())

        END

    SET @ii=@ii+1

  END

  -----二次循环结束

  END 

 SET @i=@i+1   

 END 

END 

RETURN 

END

Copy after login

4. Call function statement:

1

insert into [mytable] select * from [dbo].[fun_funcname](&#39;111|222|333|456,7894,7458|0|1|2014-01-01 12:15:16;1111|2222|3333|456,7894,7458|0|1|2014-01-01 12:15:16&#39;,&#39;;&#39;,&#39;|&#39;);

Copy after login

5. Result display:

1

select * from [mytable] ;

Copy after login

Method 2: Use BULK INSERT

The first operation of inserting large amounts of data, use Bulk to insert file data into the database

Sql code

Create database

1

2

CREATE DATABASE [db_mgr]

GO

Copy after login

Create test table

1

2

3

4

5

6

7

8

9

10

USE db_mgr

CREATE TABLE dbo.T_Student(

  F_ID [int] IDENTITY(1,1) NOT NULL,

  F_Code varchar(10) ,

  F_Name varchar(100) ,

  F_Memo nvarchar(500) ,

  F_Memo2 ntext ,

  PRIMARY KEY (F_ID)

)

GO

Copy after login

Fill test data

1

2

3

4

5

6

7

Insert Into T_Student(F_Code, F_Name, F_Memo, F_Memo2) select

&#39;code001&#39;, &#39;name001&#39;, &#39;memo001&#39;, &#39;备注&#39; union all select

&#39;code002&#39;, &#39;name002&#39;, &#39;memo002&#39;, &#39;备注&#39; union all select

&#39;code003&#39;, &#39;name003&#39;, &#39;memo003&#39;, &#39;备注&#39; union all select

&#39;code004&#39;, &#39;name004&#39;, &#39;memo004&#39;, &#39;备注&#39; union all select

&#39;code005&#39;, &#39;name005&#39;, &#39;memo005&#39;, &#39;备注&#39; union all select

&#39;code006&#39;, &#39;name006&#39;, &#39;memo006&#39;, &#39;备注&#39;

Copy after login

Open the xp_cmdshell stored procedure (open There may be security risks later)

1

2

3

4

EXEC sp_configure &#39;show advanced options&#39;, 1;

RECONFIGURE;EXEC sp_configure &#39;xp_cmdshell&#39;, 1;

EXEC sp_configure &#39;show advanced options&#39;, 0;

RECONFIGURE;

Copy after login

Use bcp to export the format file:

1

EXEC master..xp_cmdshell &#39;BCP db_mgr.dbo.T_Student format nul -f C:/student_fmt.xml -x -c -T&#39;

Copy after login

Use bcp to export the data file:

1

EXEC master..xp_cmdshell &#39;BCP db_mgr.dbo.T_Student out C:/student.data -f C:/student_fmt.xml -T&#39;

Copy after login

Clear the data in the table

1

truncate table db_mgr.dbo.T_Student

Copy after login

Use the Bulk Insert statement to batch import data files:

1

2

3

4

5

6

BULK INSERT db_mgr.dbo.T_Student

FROM &#39;C:/student.data&#39;

WITH

(

  FORMATFILE = &#39;C:/student_fmt.xml&#39;

)

Copy after login

Use OPENROWSET(BULK ):

T_Student table must already exist

1

2

INSERT INTO db_mgr.dbo.T_Student(F_Code, F_Name) SELECT F_Code, F_Name

FROM OPENROWSET(BULK N&#39;C:/student.data&#39;, FORMATFILE=N&#39;C:/student_fmt.xml&#39;) AS new_table_name

Copy after login

Example of using OPENROWSET (BULK):

tt table may not exist

1

2

SELECT F_Code, F_Name INTO db_mgr.dbo.tt

FROM OPENROWSET(BULK N&#39;C:/student.data&#39;, FORMATFILE=N&#39;C:/student_fmt.xml&#39;) AS new_table_name

Copy after login

For more solutions to the slow insertion speed or data loss of large amounts of data in Sqlserver, please pay attention to the PHP Chinese website for related articles!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What is REST API design principles? What is REST API design principles? Apr 04, 2025 am 12:01 AM

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

What are anonymous classes in PHP and when might you use them? What are anonymous classes in PHP and when might you use them? Apr 04, 2025 am 12:02 AM

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.

See all articles