SQL Server with as, simple comparison of ordinary nested statements

SQL Server with as, simple comparison of ordinary nested statements


Preface

I am a novice in data analysis and started using SQL Server this year. Due to work needs, I have been studying the use of with as in SQL Server in the past two days. After reading some senior posts, combined with my own needs in actual work, the following are some of my own experiences for the same situation as me Friends for reference.


1. What is the role of with as in SQL Server?

The with as short sentence is also called the subquery part. Define a SQL fragment, the fragment will be used by the entire SQL statement, sometimes to improve the readability of the SQL statement, sometimes it can be used in Union all as a part of providing data.

I use with as for the purpose. First, I hope the code will be more convenient to read. Second, I have seen a lot of sharing. Using with as statement will improve query efficiency than using ordinary nested query statements. Then I want to know that in my How much can be improved at work.

Two, nested query statement

1. Code

I am in the food retail industry, so I need to know the annual weather conditions in a designated area, so I built a historical weather forecast table.
tbweatherbyday: table name, data volume is about 60,000
city: field name The
following query statement, I want to query which cities have "state" in the city name

code show as below

select * from tbweatherbyday where city in
(select city from tbweatherbyday where city like'%州')

2. Query results

Query records: 13,242 records, query time: 0.238s

Nested query

Three, the way to use table variables

1. Code

code show as below

declare @t table(city nvarchar(5))
insert into @t(select city from tbweatherbyday where city like'%州')
select * from tbweatherbyday where city in(select * from @t)

2. Query results

Query records: 13242, query time: 0.278s
Table variable query

Fourth, use the with as method

1. Code

code show as below

cr: a common table expression, similar in use to table variables

with 
cr as
(select city from tbweatherbyday where city like'%州')
select * from tbweatherbyday where city in(select * from cr)

2. Query results

Query records: 13242, query time: 0.369s

with as


to sum up

Through the above comparison, we can see that the query time of the three is not much different. This result is a bit different from the conclusion I saw in the data of other predecessors. It may be a difference in the test background. Then I learned that we must unite knowledge and action. The information is only of reference value. Actual use needs to be combined with your own work, which will have a greater significance. If there are any shortcomings, please correct me, thank you @[TOC] (write the custom catalog title here)

Guess you like

Origin blog.csdn.net/weixin_45278370/article/details/115022451