Hoang  Ha

Hoang Ha

1677047502

Cách sử dụng SQL Triggers

Trong hướng dẫn này, bạn sẽ tìm hiểu: Trình kích hoạt SQL là gì, cách tạo trình kích hoạt, cách loại bỏ chúng và thời điểm sử dụng chúng để bạn có thể viết các truy vấn tốt hơn.

Trình kích hoạt MySQL giống như trình xử lý sự kiện JavaScript. Chúng không được thực hiện cho đến khi một hành động mà chúng được yêu cầu lắng nghe xảy ra.

Đây là một mô tả hữu ích về chúng từ các tài liệu MySQL:

Trình kích hoạt là một đối tượng cơ sở dữ liệu được đặt tên được liên kết với một bảng và kích hoạt khi một sự kiện cụ thể xảy ra đối với bảng. Một số cách sử dụng trình kích hoạt là để thực hiện kiểm tra các giá trị được chèn vào bảng hoặc để thực hiện các phép tính trên các giá trị liên quan đến một bản cập nhật. - Mysql.com

Trình kích hoạt rất hữu ích để tự động hóa các tác vụ lặp đi lặp lại. Bạn chỉ có thể thiết lập trình kích hoạt để thực hiện một số phép tính sau mỗi hành động cơ sở dữ liệu cụ thể. Bạn cũng có thể thiết lập trình kích hoạt để thực hiện các tác vụ xác thực dữ liệu trên bảng.

Trình kích hoạt được kích hoạt khi thao tác INSERT, UPDATEhoặc DELETExảy ra trên bảng cơ sở dữ liệu. Một trình kích hoạt được kích hoạt trên mỗi hàng, vì vậy nếu nhiều hàng dữ liệu đang được chèn hoặc xóa, thì mỗi hàng vẫn kích hoạt thiết lập hành động bằng trình kích hoạt. Trình kích hoạt có thể được thiết lập để kích hoạt trước hoặc sau một hành động.

Trong hướng dẫn này, bạn sẽ học cách tạo trình kích hoạt, cách loại bỏ chúng và khi nào chúng hữu ích.

Cách tạo Trình kích hoạt

Để tạo một trình kích hoạt mới, hãy sử dụng CREATE TRIGGERlệnh. Lệnh này có cấu trúc như sau:

CREATE TRIGGER trigger_name
trigger_time 
trigger_event
ON table_name 
FOR EACH ROW
trigger_body

Vì vậy, đây là một sự cố của mỗi dòng:

  • Từ khóa CREATE TRIGGERlà bắt buộc và được theo sau bởi tên của trình kích hoạt. Bạn sẽ sử dụng tên này để chỉ trình kích hoạt trong tương lai và để xóa trình kích hoạt nếu có nhu cầu. Tên này phải là duy nhất cho mỗi cơ sở dữ liệu.
  • The trigger_timelà một giá trị biến chỉ có thể là BEFOREhoặc AFTER. Điều này xác định liệu trình kích hoạt sẽ kích hoạt trước hay sau khi sự kiện xảy ra.
  • Đây trigger_eventlà một biến khác có một số tùy chọn có thể hạn chế. Biến này không thể là bất kỳ giá trị nào khác ngoài INSERT, UPDATEhoặc DELETE. Nó chỉ định sự kiện nào cần lắng nghe.
  • table_namelà tên của bảng mà trình kích hoạt nên xem. Đây phải là tên của một bảng hiện có trong cơ sở dữ liệu của bạn, nhưng nó có thể là một bảng trống.
  • Đây FOR EACH ROWlà phần bắt buộc khác của định nghĩa trình kích hoạt.
  • trigger_bodylà truy vấn SQL mà bạn muốn chạy khi trình kích hoạt này được kích hoạt.

Để tạo ví dụ về trình kích hoạt, tôi sẽ tạo một usersbảng đơn giản để thực hành.

CREATE TABLE
    users (
        fullname VARCHAR(120),
        email VARCHAR(120),
        username VARCHAR(30),
        password VARCHAR(60)
    );

Bây giờ, chúng ta có thể tạo một trình kích hoạt đơn giản và gắn nó vào bảng trống này. Trình kích hoạt mã hóa mật khẩu chuỗi trước khi chúng được chèn bằng MD5hàm sẽ có ý nghĩa.

CREATE TRIGGER password_hasher BEFORE INSERT ON users FOR EACH ROW
SET
    NEW.password = MD5 (NEW.password);

Ví dụ này khá đơn giản và dễ hiểu. Nhưng có một NEWtừ khóa ở đó. Từ khóa này cung cấp cho bạn quyền truy cập vào dữ liệu mới được tạo và cho phép bạn sử dụng hoặc sửa đổi các giá trị theo ý muốn.

Bạn chỉ có thể sửa đổi các giá trị này nếu bộ của bạn event_timeBEFORE. Nếu event_timeđược đặt thành AFTER, dữ liệu đã được lưu trữ trước khi đến trình kích hoạt nên không thể sửa đổi lại.  

Bạn có thể sử dụng NEWtừ khóa in INSERTUPDATEsự kiện chứ không phải DELETEsự kiện.

Ngoài ra còn có OLDtừ khóa mà bạn có thể sử dụng trong DELETEUPDATEtrình kích hoạt sự kiện cho phép bạn truy cập vào các giá trị cũ của bản ghi bị ảnh hưởng. Bạn không thể sử dụng từ khóa này cho một INSERTsự kiện vì không có bản ghi nào trước đó trước khi dữ liệu mới được tạo.

Để kiểm tra trình kích hoạt này, hãy chèn một hàng vào usersbảng:

INSERT INTO
    users
VALUES
    (
        'idris babu',
        'zubs@test.com',
        'zubby1',
        'password'
    );

Kiểm tra bảng của bạn cho các giá trị. Cậu nên có vài thứ như thế này:

Ảnh chụp màn hình-2023-02-18-at-02.14.44

Giá trị mật khẩu đã được mã hóa chính xác. 🥳

Làm thế nào để thả một kích hoạt

Sau khi tạo trình kích hoạt, bạn có thể muốn dừng thực thi trình kích hoạt vì lý do nào đó. Trong trường hợp này, bạn có thể bỏ kích hoạt.

Để thả trình kích hoạt, hãy sử dụng DROP TRIGGERlệnh. Lệnh chỉ yêu cầu tên của trình kích hoạt. Bạn có thể sử dụng lệnh như thế này:

DROP TRIGGER password_hasher;

Chạy truy vấn này sẽ xóa trình kích hoạt mà chúng tôi đã tạo ở trên và mọi bản ghi được chèn từ bây giờ sẽ không được mã hóa mật khẩu.

Để kiểm tra điều này, hãy chèn cùng một bản ghi như trước và kiểm tra kết quả.

Ảnh chụp màn hình-2023-02-18-at-02.24.21

Bản ghi mới được tạo không có mật khẩu được mã hóa.

Một điều cần lưu ý: nếu bạn xóa hoàn toàn bảng, tất cả các trình kích hoạt liên quan cũng sẽ tự động bị xóa.

Khi nào nên sử dụng Trình kích hoạt

  1. Ghi nhật ký: Bạn có thể có trình kích hoạt để tự động ghi vào bảng khác khi chèn, cập nhật hoặc xóa bản ghi khỏi bảng.
  2. Xác thực dữ liệu: Bạn có thể viết trình kích hoạt để đảm bảo dữ liệu là một loại nhất định và có thể đặt các giá trị chính xác khi cần.
  3. Đồng bộ hóa dữ liệu: Bạn có thể sử dụng trình kích hoạt để cập nhật các bảng liên quan. Ví dụ: trong bảng thương mại điện tử, mỗi khi bản ghi bán hàng được tạo, trình kích hoạt có thể cập nhật số dư của nhà cung cấp. Hoặc nếu bản ghi của nhà cung cấp bị xóa, trình kích hoạt có thể xóa tất cả sản phẩm của họ.

Bản tóm tắt

Tôi hy vọng bây giờ bạn đã hiểu trình kích hoạt SQL và thời điểm sử dụng chúng để bạn có thể viết các truy vấn tốt hơn.

Nguồn: https://www.freecodecamp.org

#sql 

What is GEEK

Buddha Community

Cách sử dụng SQL Triggers
Cayla  Erdman

Cayla Erdman

1594369800

Introduction to Structured Query Language SQL pdf

SQL stands for Structured Query Language. SQL is a scripting language expected to store, control, and inquiry information put away in social databases. The main manifestation of SQL showed up in 1974, when a gathering in IBM built up the principal model of a social database. The primary business social database was discharged by Relational Software later turning out to be Oracle.

Models for SQL exist. In any case, the SQL that can be utilized on every last one of the major RDBMS today is in various flavors. This is because of two reasons:

1. The SQL order standard is genuinely intricate, and it isn’t handy to actualize the whole standard.

2. Every database seller needs an approach to separate its item from others.

Right now, contrasts are noted where fitting.

#programming books #beginning sql pdf #commands sql #download free sql full book pdf #introduction to sql pdf #introduction to sql ppt #introduction to sql #practical sql pdf #sql commands pdf with examples free download #sql commands #sql free bool download #sql guide #sql language #sql pdf #sql ppt #sql programming language #sql tutorial for beginners #sql tutorial pdf #sql #structured query language pdf #structured query language ppt #structured query language

Cayla  Erdman

Cayla Erdman

1596441660

Welcome Back the T-SQL Debugger with SQL Complete – SQL Debugger

When you develop large chunks of T-SQL code with the help of the SQL Server Management Studio tool, it is essential to test the “Live” behavior of your code by making sure that each small piece of code works fine and being able to allocate any error message that may cause a failure within that code.

The easiest way to perform that would be to use the T-SQL debugger feature, which used to be built-in over the SQL Server Management Studio tool. But since the T-SQL debugger feature was removed completely from SQL Server Management Studio 18 and later editions, we need a replacement for that feature. This is because we cannot keep using the old versions of SSMS just to support the T-SQL Debugger feature without “enjoying” the new features and bug fixes that are released in the new SSMS versions.

If you plan to wait for SSMS to bring back the T-SQL Debugger feature, vote in the Put Debugger back into SSMS 18 to ask Microsoft to reintroduce it.

As for me, I searched for an alternative tool for a T-SQL Debugger SSMS built-in feature and found that Devart company rolled out a new T-SQL Debugger feature to version 6.4 of SQL – Complete tool. SQL Complete is an add-in for Visual Studio and SSMS that offers scripts autocompletion capabilities, which help develop and debug your SQL database project.

The SQL Debugger feature of SQL Complete allows you to check the execution of your scripts, procedures, functions, and triggers step by step by adding breakpoints to the lines where you plan to start, suspend, evaluate, step through, and then to continue the execution of your script.

You can download SQL Complete from the dbForge Download page and install it on your machine using a straight-forward installation wizard. The wizard will ask you to specify the installation path for the SQL Complete tool and the versions of SSMS and Visual Studio that you plan to install the SQL Complete on, as an add-in, from the versions that are installed on your machine, as shown below:

Once SQL Complete is fully installed on your machine, the dbForge SQL Complete installation wizard will notify you of whether the installation was completed successfully or the wizard faced any specific issue that you can troubleshoot and fix easily. If there are no issues, the wizard will provide you with an option to open the SSMS tool and start using the SQL Complete tool, as displayed below:

When you open SSMS, you will see a new “Debug” tools menu, under which you can navigate the SQL Debugger feature options. Besides, you will see a list of icons that will be used to control the debug mode of the T-SQL query at the leftmost side of the SSMS tool. If you cannot see the list, you can go to View -> Toolbars -> Debugger to make these icons visible.

During the debugging session, the SQL Debugger icons will be as follows:

The functionality of these icons within the SQL Debugger can be summarized as:

  • Adding Breakpoints to control the execution pause of the T-SQL script at a specific statement allows you to check the debugging information of the T-SQL statements such as the values for the parameters and the variables.
  • Step Into is “navigate” through the script statements one by one, allowing you to check how each statement behaves.
  • Step Over is “execute” a specific stored procedure if you are sure that it contains no error.
  • Step Out is “return” from the stored procedure, function, or trigger to the main debugging window.
  • Continue executing the script until reaching the next breakpoint.
  • Stop Debugging is “terminate” the debugging session.
  • Restart “stop and start” the current debugging session.

#sql server #sql #sql debugger #sql server #sql server stored procedure #ssms #t-sql queries

Cayla  Erdman

Cayla Erdman

1596448980

The Easy Guide on How to Use Subqueries in SQL Server

Let’s say the chief credit and collections officer asks you to list down the names of people, their unpaid balances per month, and the current running balance and wants you to import this data array into Excel. The purpose is to analyze the data and come up with an offer making payments lighter to mitigate the effects of the COVID19 pandemic.

Do you opt to use a query and a nested subquery or a join? What decision will you make?

SQL Subqueries – What Are They?

Before we do a deep dive into syntax, performance impact, and caveats, why not define a subquery first?

In the simplest terms, a subquery is a query within a query. While a query that embodies a subquery is the outer query, we refer to a subquery as the inner query or inner select. And parentheses enclose a subquery similar to the structure below:

SELECT 
 col1
,col2
,(subquery) as col3
FROM table1
[JOIN table2 ON table1.col1 = table2.col2]
WHERE col1 <operator> (subquery)

We are going to look upon the following points in this post:

  • SQL subquery syntax depending on different subquery types and operators.
  • When and in what sort of statements one can use a subquery.
  • Performance implications vs. JOINs.
  • Common caveats when using SQL subqueries.

As is customary, we provide examples and illustrations to enhance understanding. But bear in mind that the main focus of this post is on subqueries in SQL Server.

Now, let’s get started.

Make SQL Subqueries That Are Self-Contained or Correlated

For one thing, subqueries are categorized based on their dependency on the outer query.

Let me describe what a self-contained subquery is.

Self-contained subqueries (or sometimes referred to as non-correlated or simple subqueries) are independent of the tables in the outer query. Let me illustrate this:

-- Get sales orders of customers from Southwest United States 
-- (TerritoryID = 4)

USE [AdventureWorks]
GO
SELECT CustomerID, SalesOrderID
FROM Sales.SalesOrderHeader
WHERE CustomerID IN (SELECT [CustomerID]
                     FROM [AdventureWorks].[Sales].[Customer]
                     WHERE TerritoryID = 4)

As demonstrated in the above code, the subquery (enclosed in parentheses below) has no references to any column in the outer query. Additionally, you can highlight the subquery in SQL Server Management Studio and execute it without getting any runtime errors.

Which, in turn, leads to easier debugging of self-contained subqueries.

The next thing to consider is correlated subqueries. Compared to its self-contained counterpart, this one has at least one column being referenced from the outer query. To clarify, I will provide an example:

USE [AdventureWorks]
GO
SELECT DISTINCT a.LastName, a.FirstName, b.BusinessEntityID
FROM Person.Person AS p
JOIN HumanResources.Employee AS e ON p.BusinessEntityID = e.BusinessEntityID
WHERE 1262000.00 IN
    (SELECT [SalesQuota]
    FROM Sales.SalesPersonQuotaHistory spq
    WHERE p.BusinessEntityID = spq.BusinessEntityID)

Were you attentive enough to notice the reference to BusinessEntityID from the Person table? Well done!

Once a column from the outer query is referenced in the subquery, it becomes a correlated subquery. One more point to consider: if you highlight a subquery and execute it, an error will occur.

And yes, you are absolutely right: this makes correlated subqueries pretty harder to debug.

To make debugging possible, follow these steps:

  • isolate the subquery.
  • replace the reference to the outer query with a constant value.

Isolating the subquery for debugging will make it look like this:

SELECT [SalesQuota]
    FROM Sales.SalesPersonQuotaHistory spq
    WHERE spq.BusinessEntityID = <constant value>

Now, let’s dig a little deeper into the output of subqueries.

Make SQL Subqueries With 3 Possible Returned Values

Well, first, let’s think of what returned values can we expect from SQL subqueries.

In fact, there are 3 possible outcomes:

  • A single value
  • Multiple values
  • Whole tables

Single Value

Let’s start with single-valued output. This type of subquery can appear anywhere in the outer query where an expression is expected, like the WHERE clause.

-- Output a single value which is the maximum or last TransactionID
USE [AdventureWorks]
GO
SELECT TransactionID, ProductID, TransactionDate, Quantity
FROM Production.TransactionHistory
WHERE TransactionID = (SELECT MAX(t.TransactionID) 
                       FROM Production.TransactionHistory t)

When you use a MAX() function, you retrieve a single value. That’s exactly what happened to our subquery above. Using the equal (=) operator tells SQL Server that you expect a single value. Another thing: if the subquery returns multiple values using the equals (=) operator, you get an error, similar to the one below:

Msg 512, Level 16, State 1, Line 20
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Multiple Values

Next, we examine the multi-valued output. This kind of subquery returns a list of values with a single column. Additionally, operators like IN and NOT IN will expect one or more values.

-- Output multiple values which is a list of customers with lastnames that --- start with 'I'

USE [AdventureWorks]
GO
SELECT [SalesOrderID], [OrderDate], [ShipDate], [CustomerID]
FROM Sales.SalesOrderHeader
WHERE [CustomerID] IN (SELECT c.[CustomerID] FROM Sales.Customer c
INNER JOIN Person.Person p ON c.PersonID = p.BusinessEntityID
WHERE p.lastname LIKE N'I%' AND p.PersonType='SC')

Whole Table Values

And last but not least, why not delve into whole table outputs.

-- Output a table of values based on sales orders
USE [AdventureWorks]
GO
SELECT [ShipYear],
COUNT(DISTINCT [CustomerID]) AS CustomerCount
FROM (SELECT YEAR([ShipDate]) AS [ShipYear], [CustomerID] 
      FROM Sales.SalesOrderHeader) AS Shipments
GROUP BY [ShipYear]
ORDER BY [ShipYear]

Have you noticed the FROM clause?

Instead of using a table, it used a subquery. This is called a derived table or a table subquery.

And now, let me present you some ground rules when using this sort of query:

  • All columns in the subquery should have unique names. Much like a physical table, a derived table should have unique column names.
  • ORDER BY is not allowed unless TOP is also specified. That’s because the derived table represents a relational table where rows have no defined order.

In this case, a derived table has the benefits of a physical table. That’s why in our example, we can use COUNT() in one of the columns of the derived table.

That’s about all regarding subquery outputs. But before we get any further, you may have noticed that the logic behind the example for multiple values and others as well can also be done using a JOIN.

-- Output multiple values which is a list of customers with lastnames that start with 'I'
USE [AdventureWorks]
GO
SELECT o.[SalesOrderID], o.[OrderDate], o.[ShipDate], o.[CustomerID]
FROM Sales.SalesOrderHeader o
INNER JOIN Sales.Customer c on o.CustomerID = c.CustomerID
INNER JOIN Person.Person p ON c.PersonID = p.BusinessEntityID
WHERE p.LastName LIKE N'I%' AND p.PersonType = 'SC'

In fact, the output will be the same. But which one performs better?

Before we get into that, let me tell you that I have dedicated a section to this hot topic. We’ll examine it with complete execution plans and have a look at illustrations.

So, bear with me for a moment. Let’s discuss another way to place your subqueries.

#sql server #sql query #sql server #sql subqueries #t-sql statements #sql

Ruth  Nabimanya

Ruth Nabimanya

1621850444

List of Available Database for Current User In SQL Server

Introduction

When working in the SQL Server, we may have to check some other databases other than the current one which we are working. In that scenario we may not be sure that does we have access to those Databases?. In this article we discuss the list of databases that are available for the current logged user in SQL Server

Get the list of database
Conclusion

#sql server #available databases for current user #check database has access #list of available database #sql #sql query #sql server database #sql tips #sql tips and tricks #tips

Introduction to Recursive CTE

This article will introduce the concept of SQL recursive. Recursive CTE is a really cool. We will see that it can often simplify our code, and avoid a cascade of SQL queries!

Why use a recursive CTE ?

The recursive queries are used to query hierarchical data. It avoids a cascade of SQL queries, you can only do one query to retrieve the hierarchical data.

What is recursive CTE ?

First, what is a CTE? A CTE (Common Table Expression) is a temporary named result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement. For example, you can use CTE when, in a query, you will use the same subquery more than once.

A recursive CTE is one having a subquery that refers to its own name!

Recursive CTE is defined in the SQL standard.

How to make a recursive CTE?

A recursive CTE has this structure:

  • The WITH clause must begin with “WITH RECURSIVE”
  • The recursive CTE subquery has two parts, separated by “UNION [ALL]” or “UNION DISTINCT”:
  • The first part produces the initial row(s) for the CTE. This SELECT does not refer to the CTE name.
  • The second part recurses by referring to the CTE name in its FROM clause.

Practice / Example

In this example, we use hierarchical data. Each row can have zero or one parent. And it parent can also have a parent etc.

Create table test (id integer, parent_id integer);

insert into test (id, parent_id) values (1, null);

insert into test (id, parent_id) values (11, 1);
insert into test (id, parent_id) values (111, 11);

insert into test (id, parent_id) values (112, 11);

insert into test (id, parent_id) values (12, 1);

insert into test (id, parent_id) values (121, 12);

For example, the row with id 111 has as ancestors: 11 and 1.

Before knowing the recursive CTE, I was doing several queries to get all the ancestors of a row.

For example, to retrieve all the ancestors of the row with id 111.

While (has parent)

	Select id, parent_id from test where id = X

With recursive CTE, we can retrieve all ancestors of a row with only one SQL query :)

WITH RECURSIVE cte_test AS (
	SELECT id, parent_id FROM test WHERE id = 111
	UNION 
	SELECT test.id, test.parent_id FROM test JOIN cte_test ON cte_test.id = test.parent_id

) SELECT * FROM cte_test

Explanations:

  • “WITH RECURSIVE”:

It indicates we will make recursive

  • “SELECT id, parent_id FROM test WHERE id = 111”:

It is the initial query.

  • “UNION … JOIN cte_test” :

It is the recursive expression! We make a jointure with the current CTE!

Replay this example here

#sql #database #sql-server #sql-injection #writing-sql-queries #sql-beginner-tips #better-sql-querying-tips #sql-top-story