Microsoft 70-761 Querying Data with Transact-SQL Flashcards

Correct Answer: B
With X_ABORT ON the INSERT INTO statement and the transaction will be rolled back when an error is raised, it would then not be possible to ROLLBACK it again in the IF XACT_STATE() <> O ROLLBACK TRANSACTION statement.
Note: A transaction is correctly defined for the INSERT INTO ..VALUES statement, and if there is an error in the transaction it will be caught and the transaction will be rolled back, finally an error 51000 will be raised.
Note: When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back.
XACT_STATE is a scalar function that reports the user transaction state of a current running request. XACT_STATE indicates whether the request has an active user transaction, and whether the transaction is capable of being committed.
The states of XACT_STATE are:
✑ 0 There is no active user transaction for the current request.
✑ 1 The current request has an active user transaction. The request can perform any actions, including writing data and committing the transaction.
✑ 2 The current request has an active user transaction, but an error has occurred that has caused the transaction to be classified as an uncommittable transaction.

Correct Answer: B
The WHERE clause of the third line should be WHERE ProjectID IS NULL, as we want to count the tasks that are not associated with a project.

Correct Answer: Please see explanation
1 WITH ParentCategories pc (CategoryID, Name, PatentCategoryID) AS (SELECT c.categoryID,c.name,c.parentcategoryid
2 FROM sales.categories c
3 WHERE parentcategoryid is not null
4 )
5 SELECT * FROM parentcategories
Note: On Line 1 replace c with WITH ParentCategories pc (CategoryID, Name, PatentCategoryID) AS
Note: The basic syntax structure for a CTE is:
WITH expression_name [( column_name [,…n] ) ]
AS -
( CTE_query_definition )

Correct Answer: Please see explanation
1 SELECT p.productname
2 FROM Production.categories AS c
3 inner join production.products as p on c.categoryid=p.categoryid
4 WHERE c.categoryname = ‘Beverages’
Note: On line 3 change * to =

SELECT AVG(normalizedreading) as AverageReading, Nearestmountain(location) AS Mountain FROM GroundSensors WHERE normalizedreading is not NULL GROUP BY Nearestmountain(location)

Correct Answer: Please see explanation
1. DELETE from sales.orders where status=’Canceled’
Note: On line 1 change calceled to Canceled
Example: Using the WHERE clause to delete a set of rows
The following example deletes all rows from the ProductCostHistory table in the AdventureWorks2012 database in which the value in the StandardCost column is more than 1000.00.
DELETE FROM Production.ProductCostHistory
WHERE StandardCost > 1000.00;

Correct Answer: Please see explanation
1 SELECT top 3 lastname,salesYTD
2 FROM Person AS p INNER JOIN SalesPerson AS s
3 ON p.PersonID = s.SalesPersonID
4 WHERE territoryid is not null
5 order by salesytd desc
Note:
On line 4 add a not before null.
On line 5 change dsec to desc.

Correct Answer: C
Would list the customers with duplicates, which would equal the number of accounts.
Incorrect Answers:
A: INTERSECT returns distinct rows that are output by both the left and right input queries operator.
B: Would list the customers without duplicates.
D: Number of customers.
F: EXCEPT returns distinct rows from the left input query that aren’t output by the right input query.

RAISERROR generates an error message and initiates error processing for the session. RAISERROR can either reference a user-defined message stored in the sys.messages catalog view or build a message dynamically. The message is returned as a server error message to the calling application or to an associated
CATCH block of a TRY”¦CATCH construct. New applications should use THROW instead.
Note: RAISERROR syntax:
RAISERROR( { msg_id | msg_str | @local_variable }
{ ,severity ,state }
[,argument [ ,…n] ] )
[WITH option [ ,…n] ]
The LOG option logs the error in the error log and the application log for the instance of the Microsoft SQL Server Database Engine.


To compare char(5) and nchar(5) an implicit conversion has to take place.
Explicit conversions use the CAST or CONVERT functions, as in line number 6.


Correct Answer: A
ShortestLineTo (geometry Data Type) Returns a LineString instance with two points that represent the shortest distance between the two geometry instances. The length of the LineString instance returned is the distance between the two geometry instances.
STLength (geometry Data Type) returns the total length of the elements in a geometry instance.

B. No

Box 1: COALESCE -
COALESCE evaluates the arguments in order and returns the current value of the first expression that initially does not evaluate to NULL.
Box 2: T.UserID, p.UserID, -1 -
✑ Return each task’s owner if the task has an owner.
✑ If a task has no owner, but is associated with a project that has an owner, return the project’s owner.
✑ Return the value -1 for all other cases.
Box 3: RIGHT JOIN -
The RIGHT JOIN keyword returns all rows from the right table (table2), with the matching rows in the left table (table1). The result is NULL in the left side when there is no match. Here the right side could be NULL as the projectID of the task could be NULL.


B. No

B. No



Correct Answer: D
datetime2 Defines a date that is combined with a time of day that is based on 24-hour clock. datetime2 can be considered as an extension of the existing datetime type that has a larger date range, a larger default fractional precision, and optional user-specified precision.
Incorrect Answers:
B, C, E: NEWQSEQUENTIALID creates a GUID that is greater than any GUID previously generated by this function on a specified computer since Windows was started. A GUID uses more space then IDENTITY value.

Correct Answer: A
Incorrect Answers:
B: The count should be on the Cust instance of Sales.Customers as it is to the right side of the join.
C: Need a WHERE statement with an IS NULL clause.
D: Must use a LEFT JOIN to obtain the NULL values.

Wildcard character %: Any string of zero or more characters.
For example: If the LIKE ‘5%’ symbol is specified, the Database Engine searches for the number 5 followed by any string of zero or more characters.

Correct Answer: H
To retain the nonmatching information by including nonmatching rows in the results of a join, use a full outer join. SQL Server provides the full outer join operator,
FULL OUTER JOIN, which includes all rows from both tables, regardless of whether or not the other table has a matching value.
Incorrect Answers:
A: Inner joins return rows only when there is at least one row from both tables that matches the join condition. Inner joins eliminate the rows that do not match with a row from the other table.
B: INTERSECT returns distinct rows that are output by both the left and right input queries operator.
D: EXCEPT returns distinct rows from the left input query that aren’t output by the right input query.
E: UNION specifies that multiple result sets are to be combined and returned as a single result set, but this will not work here as the CustomerID column values do not match.
F: UNION ALL incorporates all rows into the results. This includes duplicates. If not specified, duplicate rows are removed.
G: A cross join would produce the Cartesian product of the two tables.


You have a database named DB1 that contains a temporal table named Sales.Customers.
You need to create a query that returns the credit limit that was available to each customer in DB1 at the beginning of 2017.
Which query should you execute?
A. SELECT
CustomerID,
CustomerName,
CreditLimit
FROM
Sales.Customers
FOR SYSTEM TIME CONTAINED IN 2017-01-01 00:00:00’);
B. SELECT
CustomerID,
CustomerName,
CreditLimit
FROM
Sales.Customers
FOR SYSTEM TIME CONTAINED IN (‘2017-01-01’);
C. SELECT
CustomerID,
CustomerName,
CreditLimit
FROM
Sales.Customers
FOR SYSTEM TIME AS OF 2017-01-01’;
D. SELECT
CustomerID,
CustomerName,
CreditLimit
FROM
Sales.Customers
FOR SYSTEM TIME ALL;
Correct Answer: C
AS OF: Returns a table with a rows containing the values that were actual (current) at the specified point in time in the past.
Incorrect Answers:
A, B: CONTAINED IN has two parameters: CONTAINED IN (<start_date_time> , <end_date_time>)</end_date_time></start_date_time>



Box 1: SELECT CAST (NULL AS INT) AS ParentTaskID, etc.
This statement selects all tasks with task level 0.
The ParentTaskID could be null so we should use CAST (NULL AS INT) AS ParentTaskID.
Box 2: UNION -
We should use UNION and not UNION ALL as we do not went duplicate rows.
UNION specifies that multiple result sets are to be combined and returned as a single result set.
Incorrect Answers:
Not UNION ALL: ALL incorporates all rows into the results. This includes duplicates. If not specified, duplicate rows are removed.
Box 3, Box 4, Box 5:
These statements select all tasks with task level >0.















































































































[AS]
BEGIN -
function_body
RETURN scalar_expression -
END -
[;]
Box 4: @OrderPrice * @CalculatedTaxRate
Calculate the price including tax.
Box 5: END -
Transact-SQL Scalar Function Syntax include theBEGIN ..END construct.
























































