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.
You need to create a database object that meets the following requirements:
✑ accepts a product identifies as input
calculates the total quantity of a specific product, including quantity on hand and quantity on order
✑ caches and reuses execution plan
✑ returns a value
✑ can be called from within a SELECT statement
✑ can be used in a JOIN clause
What should you create?
A. a temporary table that has a columnstore index
B. a user-defined table-valued function
C. a memory-optimized table that has updated statistics
D. a natively-complied stored procedure that has an OUTPUT parameter
B. a user-defined table-valued function
A table-valued user-defined function can also replace stored procedures that return a single result set. The table returned by a user-defined function can be referenced in the FROM clause of a Transact-SQL statement, but stored procedures that return result sets cannot.
Note: This question is part of a series of questions that present the same scenario. Each question in the series contains a unique solution that might meet the stated goals.
Some question sets might have more than one correct solution, while others might not have a correct solution.
After you answer a question in this section. You will NOT be able to return to it. As result, these questions will not appear in the review screen.
You create a table named Products by running the following Transact-SQL statement:
CREATE TABLE Products
ProductID int IDENTITY (1, 1), NOT NULL PRIMARY KEY,
ProductName nvarchar (100), NULL,
UnitPrice decimal (18, 2) NOT NULL,
UnitsInStock int NOT NULL,
UnitsOnOrder int NULL
You have the following stored procedure:
CREATE PROCEDURE InsertProduct
@ProductName nvarchar(100),
@UnitPrice decimal (18, 2),
@UnitsInStock int,
@UnitsOnOrder int
AS
BEGIN
INSERT INTO Products (ProductName, UnitPrice, UnitsInStock, UnitsOnOrder)
VALUES (@ProductName, @UnitPrice, @UnitsInStock, @UnitsOnOrder)
END
You need to modify the stored procedure to meet the following new requirements:
Co Insert product records as single unit of work.
co Return error number 51000 when: product fails to insert into the database.
co If product record insert operation fails, the product information must not be permanently written to the database.
Solution: You run the following Transact-SQL statement:
ALTER PROCEDURE InsertProduct
@ProductName nvarchar (100),
@UnitPrice decimal (18, 2),
@UnitsInStock int,
@UnitsOnOrder int
AS
BEGIN
SET XACT ABORT ON
BEGIN TRY
BEGIN TRANSACTION
INSERT INTO Products (ProductName, UnitPrice, UnitsInStock, UnitsOnOrder)
VALUES (@ProductName, @UnitPrice, @UnitsInStock, @UnitsOnOrder)
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF XACT_STATE () <> 0 ROLLBACK TRANSACTION
THROW 51000, ‘The product could not be created, 1
END CATCH
END
Does the solution meet the goal?
A. Yes
B. No
B. No
You create a table named Products by running the following Transact-SQL statement:
CREATE TABLE Products
ProductID int IDENTITY (1, 1), NOT NULL PRIMARY KEY,
ProductName nvarchar (100), NULL,
UnitPrice decimal (18, 2) NOT NULL,
UnitsInStock int NOT NULL,
UnitsOnOrder int NULL
You have the following stored procedure:
CREATE PROCEDURE InsertProduct
@ProductName nvarchar(100),
@UnitPrice decimal (18, 2),
@UnitsInStock int,
@UnitsOnOrder int
AS
BEGIN
INSERT INTO Products (ProductName, UnitPrice, UnitsInStock, UnitsOnOrder)
VALUES (@ProductName, @UnitPrice, @UnitsInStock, @UnitsOnOrder)
END
You need to modify the stored procedure to meet the following new requirements:
co Insert product records as single unit of work.
c Return error number 51000 when a product fails to insert into the database.
co If product record insert operation fails, the product information must not be permanently written to the database.
Solution: You run the following Transact-SQL statement:
ALTER PROCEDURE InsertProduct
@ProductName nvarchar (100),
@UnitPrice decimal (18, 2),
@UnitsInStock int,
@UnitsOnOrder int
AS
BEGIN
BEGIN TRY
BEGIN TRANSACTION
INSERT INTO Products (ProductName, UnitPrice, UnitsInStock, UnitsOnOrder)
VALUES (@ProductName, @UnitPrice, @UnitsInStock, @UnitsOnOrder)
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION
RAISERROR (51000,16, 1)
END CATCH
END
Does the solution meet the goal?
A. Yes
B. No
B. No
Correct Answer: A
The OUTPUT Clause returns information from, or expressions based on, each row affected by an INSERT, UPDATE, DELETE, or MERGE statement. These results can be returned to the processing application for use in such things as confirmation messages, archiving, and other such application requirements. The results can also be inserted into a table or table variable. Additionally, you can capture the results of an OUTPUT clause in a nested INSERT, UPDATE, DELETE, or MERGE statement, and insert those results into a target table or view.
Note: If the column modified by the .RITE clause is referenced in an OUTPUT clause, the complete value of the column, either the before image in deleted.column_name or the after image in inserted.column_name, is returned to the specified column in the tablevariable.
Incorrect Answers:
D: The deleted.Creditlimit should be inserted in the second column, the OldCreditLimit column, not the third column.
A. SELECT COUNT(*) FROM (SELECT AcctNo FROM tblDepositAcct INTERSECT SELECT AcctNo FROM tblLoanAcct) R
B. SELECT COUNT(*) FROM (SELECT CustNo FROM tblDepositAcct UNION SELECT CustNo FROM tblLoanAcct) R
C. SELECT COUNT(*) FROM (SELECT CustNoFROM tblDepositAcct UNION ALL SELECT CustNo FROM tblLoanAcct) R
D. SELECT COUNT (DISTINCT D.CustNo) FROM tblDepositAcctD, tblLoanAcct L WHERE D.CustNo = L.CustNo
E. SELECT COUNT(DISTINCT L.CustNo) FROM tblDepositAcct D RIGHT JOIN tblLoanAcct L ON D.CustNo = L.CustNo WHERE D.CustNo IS NULL
F. SELECT COUNT(*) FROM (SELECT CustNo FROM tblDepositAcct EXCEPT SELECT CustNo FROM tblLoanAcct) R
G. SELECT COUNT (DISTINCT COALESCE(D.CustNo, L.CustNo)) FROM tblDepositAcct D FULL JOIN tblLoanAcct L ON D.CustNo = L.CustNo WHERE D.CustNo IS NULL OR L.CustNo IS NULL
H. SELECT COUNT(*) FROM tblDepositAcct D FULL JOIN tblLoanAcct L ON D.CustNo = L.CustNo
F. Option F
Correct Answer: B
Mathematical equation will only return 10 % of the value.
B. No
The answer is B.No.
Both insert statements are executed seperately, so failure of one won’t impact another.
A. Yes
B. No
Box 1: UPDATE T SET T.EndTime = P.EndTime
We are updating the EndTime column in the Task table.
Box 2: FROM Task AS T -
Where are updating the task table.
Box 3:INNER JOIN Project AS P on T.ProjectID = P.ProjectID
We join with the Project table (on the ProjectID columnID column).
Box 4: WHERE P.EndTime is NOT NULL AND T.EndTime is NULL
We select the columns in the Task Table where the EndTime column in the Project table has a value (NOT NULL),but where it is NULL in the Task Table.
B. No
Note: This question is part of a series of questions that present the same scenario. Each question in the series contains a unique solution that might meet the stated goals.
Some question sets might have more than one correct solution, while others might not have a correct solution.
After you answer a question in this section. You will NOT be able to return to it. As a result, these questions will not appear in the review screen.
You have a table named Products that stores information about products your company sells. The table has a column named ListPrice that stores retail pricing information
for products.
Some products are used only internally by the company. Records for these products are maintained in the Products table for inventory purposes. The price for each of these
products is $0.00. Customers are not permitted to order these products.
You need to increase the list price for products that cost less than $100 by 10 percent. You must only increase pricing for products that customers are permitted to order.
Solution: You run the following Transact-SQL statement:
UPDATE Production.Products
SET ListPrice = ListPrice 1.1
WHERE ListPrice
BETWEEN .01 and 99.99
Does the solution meet the goal?
A. Yes
B. No
A. Yes
Note: This question is part of a series of questions that present the same scenario. Each question in the series contains a unique solution that might meet the stated goals.
Some question sets might have more than one correct solution, while others might not have correct solution.
After you answer a question in this section. You will NOT be able to return to it. As a result, these questions will not appear in the review screen.
You have a table named Products that stores information about products your company sells. The table has a column named ListPrice that stores retail pricing information
for products.
Some products are used only internally by the company. Records for these products are maintained in the Products table for inventory purposes. The price for each of these
products is $0.00. Customers are not permitted to order these products.
You need to increase the list price for products that cost less than $100 by 10 percent. You must only increase pricing for products that customers are permitted to order.
Solution: You run the following Transact-SQL statement:
UPDATE Production.Products
SET ListPrice = ListPrice 1.1
WHERE ListPrice
BETWEEN 0 and 100
Does the solution meet the goal?
A. Yes
B. No
B. No
Correct Answer: Answer: B
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>
Note: This question is part of a series of questions that use the same or similar answer choices. An answer choice may be correct for more than one question in the series. Each question is independent of the other questions in this series. Information and details provided in a question apply only to that question.
You have a database that contains several connected tables. The tables contain sales data for customers in the United States only.
You need to create a query that generates sample data for a sales table in the database. The query must include every product in the inventory for each customer.
Which statement clause should you use?
A. GROUP BY
B. MERGE
C. GROUP BY ROLLUP
D. LEFT JOIN
E. GROUP BY CUBE
F. CROSS JOIN
G. PIVOT
H. UNPIVOT
C. GROUP BY ROLLUP
Note: This question is part of a series of questions that use the same or similar answer choices. An answer choice may be correct for more than one question in the series. Each question is independent of the other questions in this series. Information and details provided in a question apply only to that question.
You have a database that contains several connected tables. The tables contain sales data for customers in the United States only.
All the sales data is stored in a table named table1. You have a table named table2 that contains city names.
You need to create a query that lists only the cities that have no sales.
Which statement clause should you add to the query?
A. GROUP BY
B. MERGE
C. GROUP BY ROLLUP
D. LEFT JOIN
E. GROUP BY CUBE
F. CROSS JOIN
G. PIVOT
H. UNPIVOT
D. LEFT JOIN
A. GROUP BY
B. DECLARE @startedIasks TABLE(TaskId int, ProjectId int)
UPDATE Task SET StartTime GETDATE () OUTPUT deleted.IaskId, deleted.ProjectId INIO @startedTasks
WHERE StartTime is NULL
SELECT COUNT(*) FROM EstartedTasks WHERE ProjectId IS NULL
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 AS OF 2017-01-01 00:00:00’:
C.
SELECT
CustomerID,
CustomerName,
CreditLimit
FROM
Sales.Customers
FOR SYSTEM TIME CONTAINED IN (‘2016-12-31’, ‘2017-01-01’);
D.
SELECT
CustomerID,
CustomerName,
CreditLimit
FROM
Sales.Customers
FOR SYSTEM_TIME BETWEEN ‘2016-12-31’ AND ‘2017-01-01’);
Correct Answer: B
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>
B. a user-defined scalar function
User-defined scalar functions are execution plans that accept parameters, perform an action such as a complex calculation, and returns the result of that action as a value. The return value can either be a single scalar value or a result set. Furthermore the execution plan is cached and reusable.
User-defined scalar functions can also be called from within a SELECT statement and can be used in a JOIN clause.
Incorrect Answers:
A: Using extended stored procedures is not recommended as they has been deprecated. CLR Integration should be used instead of extended stored procedures.
C: Stored procedures cannot be used in a SELECT statement or in a JOIN clause.
D: A temporary table is a result set and not a value.
You create a table by running the following Transact-SQL statement:
CREATE TABLE Customers
CustomerID int NOT NULL PRIMARY KEY CLUSTERED,
FirstName nvarchar (100) NOT NULL,
LastName nvarchar (100) NOI NULL,
TaxIdNumber varchar (20) NOT NULL,
Address nvarchar (1024) NOT NULL,
Annua1Revenue decimal (19,2) NOT NULL,
DateCreated datetime2 (2) NOT NULL,
ValidFrom datetime2(2) GENERATED ALWAYS AS ROW START NOT NULL,
ValidTo datetime2 (2) GENERATED ALWATS AS ROW END NOT NULL,
PERIOD FOR SYSTEM TIME (ValidFrom, ValidTo)
WITH (SYSTEM VERSIONING = ON (HISTORY TABLE CustomersHistory))
You are developing a report that aggregates customer data only for the year 2014. The report requires that the data be denormalized.
You need to return the data for the report.
Which Transact-SQL statement should you run?
A. SELECT FirstName, LastName, SUM (Annual Revenue)
FROM Customers
GROUP BY GROUPING SETS ((FirstName, LastName, AnnualRevenue), () )
ORDER BY FirstName, LastName, AnnualRevenue
B. SELECT CustomerID, FirstName, LastName, TaxIdNumber, Address, AnnualRevenue, DateCreated, ValidFrom, ValidTo
FROM Customers
FOR SYSTEM TIME ALL ORDER BY ValidFrom
C. SELECT c.CustomerID, C.FirstName, c.LastName, c.Address, c.ValidFrom, c.ValidTo
FROM Customers AS
ORDER BY c.CustomerID
FOR JSON AUTO, ROOT (“Customers’)
D. SELECT x FROM (SELECT CustomerID, FirstName, LastName, Address, AnnualRevenue, DateCreated
FROM Customers) AS Customers PIVOI (AVG (AnnualRevenue)
FOR DateCreated IN([2014])) AS PivotCustomers
ORDER BY LastName, FirstName
E. SELECT CustomerID, G (Annua1Revenue)
AS AverageAnnualRevenue, FirstName, LastName, Address, DateCreated
FROM Customers WHERE YEAR(DateCreated) >= 2014
GROUP BY CustomerID, FirstName, LastName, Address, DateCreated
F. SELECT c.CustomerID, c.FirstName, c.LastName, c.Address, c.ValidFrom, c.ValidTo
FROM Customers AS C ORDER BY c.CustomerID FOR XML PATH (“‘CustomerData’), root (‘Customers’)
G. SELECT CustomerID, FirstName, LastName, TaxIdNumber, Address, ValidFrom, ValidTo
FROM Customers FOR SYSTEM TIME
BETWEEN ‘2014-01-01 00:00:00.000000’ AND 2015-01-01 00:00:00.000000’
H. SELECT CustomerID, FirstName, LastName, TaxIdNumber, Address, ValidFrom, Validlo
FROM Customers
WHERE DateCreated
BETWEEN ‘20140101’ AND ‘20141231’
G. SELECT CustomerID, FirstName, LastName, TaxIdNumber, Address, ValidFrom, ValidTo
FROM Customers FOR SYSTEM TIME
BETWEEN ‘2014-01-01 00:00:00.000000’ AND 2015-01-01 00:00:00.000000’
You create a table by running the following Transact-SQL statement:
CREATE TABLE Customers
CustomerID int NOT NULL PRIMARY KEY CLUSTERED,
FirstName nvarchar(100) NOT NULL,
LastName nvarchar (100) NOT NULL,
TaxIdNumber varchar(20) NOT NULL,
Address nvarchar (1024) NOT NULL,
Annua1Revenue decimal (19,2) NOT NULL,
DateCreated datetime2 (2) NOT NULL,
ValidFrom datetime2 (2) GENERATED ALWAYS AS ROW START NOT NULL,
ValidTo datetime2 (2) GENERATED ALWATS AS ROW END NOT NULL,
PERIOD FOR SYSTEM TIME (ValidFrom, ValidTo)
WITH (SYSTEM_VERSIONING ON (HISTORY TABLE CustomersHistory))
You need to return normalized data for all customers that were added in the year 2014.
Which Transact-SQL statement should you run?
A. SELECT FirstName, LastName, SUM (Annua1Revenue)
FROM Customers
GROUP BY GROUPING SETS((FirstName, LastName, AnnualRevenue), ())
ORDER BY FirstName, LastName, Annual Revenue
B. SELECT FirstName, LastName, Address
FROM Customers
FOR SYSTEM TIME ALL ORDER BY ValidFrom
C. SELECT c.CustomerID, c.FirstName, c.LastName, c.Address, c,ValidFrom, c.ValidTo
FROM Customers AS c
ORDER BY c. CustomerID
FOR JSON AUTO, ROOT (‘Customers’)
D. SELECT FROM (SELECT CustomerID, FirstName, LastMame, Address, AnnualRevenue, DateCreated
FROM Customers) AS Customers PIVOT (AVG (Annua1Revenue)
FOR DateCreated IN([2014J)) AS PivotCustomers
ORDER BY LastName, FirstName
E. SELECT CustomerID, AVG(AnnualRevenue)
AS AverageAnnualRevenue, FirstName, LastName, Address, DateCreated
FROM Customers WHERE YEAR(DateCreated) >= 2014
GROUP BY CustomerID, FirstName, LastName, Address, DateCreated
F. SELECT c.CustomerID, c.FirstName, c.LastName, c.Address, c.ValidFrom, c.ValidTo
FROM Customers AS c ORDER BY c.CustomerID
FOR XML PATH (‘CustomerData’), root (‘Customers’)
G. SELECT CustomerID, FirstName, LastName, TaxIdNumber, Address, ValidFrom, ValidTo
FROM Customers FOR SYSTEM TIME
BETWEEN ‘2014-01-01 00:00:00.000000’ AND ‘2015-01-01 00:00:00.000000’
H. SELECT CustomerID, FirstName, LastName, TaxIdNumber, Address, ValidFrom, ValidTo
FROM Customers
WHERE DateCreated
BETWEEN ‘20140101’ AND 20141231’
G. SELECT CustomerID, FirstName, LastName, TaxIdNumber, Address, ValidFrom, ValidTo
FROM Customers FOR SYSTEM TIME
BETWEEN ‘2014-01-01 00:00:00.000000’ AND ‘2015-01-01 00:00:00.000000’
You run the following Transact-SQL statement:
CREATE TABLE Customers
CustomerID int NOT NULL PRIMARY KEY CLUSTERED,
FirstName nvarchar(100) NOT NULL,
LastName nvarchar(100) NOT NULL,
TaxIdNumber varchar (20) NOT NULL,
Address nvarchar (1024) NOT NULL,
AnnualRevenue decimal (19,2) NOT NULL,
DateCreated datetime2(2) NOT NULL,
ValidFrom datetime2 (2) GENERATED ALWAYS AS ROW START NOT NULL,
ValidTo datetime2 (2) GENERATED ALWATS AS ROW END NOT NULL,
PERIOD FOR SYSTEM TIME (ValidFrom, ValidTo)
WITH (SYSTEM_VERSIONING ON (HISTORY TABLE CustomersHistory))
You need to return the total annual revenue for all customers, followed by row for each customer that shows the customer’s name and annual revenue.
Which Transact-SQL statement should you run?
A. SELECT FirstName, LastName, 8UM(Annua1Revenue)
FROM Customers
GROUP BY GROUPING SETS ( (FirstName, LastName, AnnualRevenue), ())
ORDER BY FirstName, LastName, AnnualRevenue
B. SELECT FirstName, LastName, Address
FROM Customers
FOR SYSTEM TIME ALL ORDER BY ValidFrom
C. SELECT c.CustomerID, C.FirstName, c.LastName, c.Address, c.ValidFrom, c.ValidTo
FROM Customers AS c
ORDER BY c. CustomerID
FOR JSON AUTO, ROOT (‘Customers’)
D. SELECT * FROM (SELECT CustomerID, FirstName, LastName, Address, AnnualRevenue, DateCreated
FROM Customers) AS Customers PIVOI (AVG (Annua1Revenue)
FOR DateCreated IN([2014])) AS PivotCustomers
ORDER BY LastName, FirstName
E. SELECT CustomerID, AVG(AnnualRevenue)
AS AverageAnnualRevenue, FirstName, LastName, Address, DateCreated
FROM Customers WHERE YEAR (DateCreated) >= 2014
GROUP BY CustomerID, FirstName, LastName, Address, DateCreated
F. SELECT c.CustomerID, C.FirstName, c.LastName, c.Address, c.ValidFrom, c.Validlo
FROM Customers AS c ORDER BY c.CustomerID
FOR XML PATH (‘CustomerData’), root (‘Customers’)
G. SELECT CustomerID, FirstName, LastName, TaxIdNumber, Address, ValidFrom, ValidTo
FROM Customers FOR SYSTEM TIME
BETWEEN 2014-01-01 00:00:00.000000’ AND $2015-01-01 00:00:00.0000001
H. SELECT CustomerID, FirstName, LastName, TaxIdNumber Address, ValidFrom, Validto
FROM Customers
WHERE DateCreated
BETWEEN 20140101’ AND 20141231’
A. SELECT FirstName, LastName, 8UM(Annua1Revenue)
FROM Customers
GROUP BY GROUPING SETS ( (FirstName, LastName, AnnualRevenue), ())
ORDER BY FirstName, LastName, AnnualRevenue
Note: This question is part of a series of questions that use the same or similar answer choices. An answer choice may be correct for more than one question in the series.
Each question is independent of the other questions in this series. Information and details provided in a question apply only to that question.
You create a table by running the following Transact-SQL statement:
CREATE TABLE Customers (
CustomerID int NOT NULL PRIMARY KEY CLUSTERED,
FirstName nvarchar (100) NOT NULL,
LastName nvarchar (100) NOT NULL,
TaxIdNumber varchar (20) NOT NULL,
Address nvarchar (1024) NOT NULL,
AnnualRevenue decimal(19,2) NOT NULL,
DateCreated datetime2(2) NOT NULL,
ValidFrom datetime2 (2) GENERATED ALWAYS AS ROW START NOT NULL,
ValidTo datetime2 (2) GENERATED ALWATS AS ROW END NOT NULL,
PERIOD FOR SYSTEM TIME (ValidFrom, ValidIo)
WITH (SYSTEM VERSIONING = ON (HISTORY TABLE = CustomersHistory))
You need to develop a query that meets the following requirements:
c Output data by using tree-like structure.
Allow mixed content types.
co Use custom metadata attributes.
Which Transact-SQL statement should you run?
A. SELECT FirstName, LastName, 8UM(Annua1Revenue)
FROM Customers
GROUP BY GROUPING SETS( (FirstName, LastName, AnnualRevenue), ())
ORDER BY FirstName, LastName, AnnualRevenue
B. SELECT FirstName, LastName, Address
FROM Customers
FOR SYSTEM TIME ALL ORDER BY ValidFrom
C. SELECT c.CustomerID, c.FirstName, c.LastName, c.Address, c.Validfrom, c.Validlo
FROM Customers AS
ORDER BY c.CustomerID
FOR JSON AUTO, ROOT (‘Customers’)
D. SELECT * FROM (SELECT CustomerID, FirstName, LastName, Address, AnnualRevenue, DateCreated
FROM Customers) AS Customers PIVOT (AVG (AnnualRevenue)
FOR DateCreated IN([2014])) AS PivotCustomers
ORDER BY LastName, FirstName
E. SELECT CustomerID, AVG (Annua1Revenue)
AS AverageAnnualRevenue, FirstName, LastName, Address, DateCreated
FROM Customers WHERE YEAR (DateCreated) >= 2014
GROUP BY CustomerID, FirstName, LastName, Address, DateCreated
F. SELECT c. CustomerID, c.FirstName, c.LastName, c.Address, c.ValidFrom, c.ValidTo
FROM Customers AS c ORDER BY c.CustomerID
FOR XML PATH (‘CustomerData’), root (‘Customers’)
G. SELECT CustomerID, FirstName, LastName, TaxIdNumber, Address, ValidFrom, ValidTo
FROM Customers FOR SYSTEM IIME
BETWEEN ‘2014-01-01 00:00:00.000000’ AND ‘2015-01-01 00:00:00.000000’
H. SELECT CustomerID, FirstName, LastName, TaxIdNumber, Address, ValidFrom, ValidTo
FROM Customers
WHERE DateCreated
BETWEEN 20140101’ AND ‘20141231’
F. SELECT c. CustomerID, c.FirstName, c.LastName, c.Address, c.ValidFrom, c.ValidTo
FROM Customers AS c ORDER BY c.CustomerID
FOR XML PATH (‘CustomerData’), root (‘Customers’)
You need to create a database object that meets the following requirements:
✑ accepts a product identifies as input
✑ calculates the total quantity of a specific product, including quantity on hand and quantity on order
✑ caches and reuses execution plan
✑ returns a value
✑ can be called from within a SELECT statement
✑ can be used in a JOIN clause
What should you create?
A. an extended stored procedure
B. a user-defined table-valued function
C. a user-defined stored procedure that has an OUTPUT parameter
D. a memory-optimized table that has updated statistics
B. a user-defined table-valued function
Note: This question is part of a series of questions that present the same scenario. Each question in the series contains a unique solution that might meet the stated goals. Some question sets might have more than one correct solution, while others might not have a correct solution.
After you answer a question in this section, you will NOT be able to return to it. As a result, these questions will not appear in the review screen.
You are building a stored procedure that will be used by hundreds of users concurrently.
You need to store rows that will be processed later by the stored procedure. The object that stores the rows must meet the following requirements:
✑ Be indexable
✑ Contain up-to-date statistics
✑ Be able to scale between 10 and 100,000 rows
The solution must prevent users from accessing one another’s data.
Solution: You create a global temporary table in the stored procedure.
Does this meet the goal?
A. Yes
B. No
A. Yes
Note: This question is part of a series of questions that present the same scenario. Each question in the series contains a unique solution that might meet the stated goals. Some question sets might have more than one correct solution, while others might not have a correct solution.
After you answer a question in this section, you will NOT be able to return to it. As a result, these questions will not appear in the review screen.
You are building a stored procedure that will be used by hundreds of users concurrently.
You need to store rows that will be processed later by the stored procedure. The object that stores the rows must meet the following requirements:
✑ Be indexable
✑ Contain up-to-date statistics
✑ Be able to scale between 10 and 100,000 rows
The solution must prevent users from accessing one another’s data.
Solution: You create a local temporary table in the stored procedure.
Does this meet the goal?
A. Yes
B. No
B. No
Note: This question is part of a series of questions that present the same scenario. Each question in the series contains a unique solution that might meet the stated goals. Some question sets might have more than one correct solution, while others might not have a correct solution.
After you answer a question in this section, you will NOT be able to return to it. As a result, these questions will not appear in the review screen.
You are building a stored procedure that will be used by hundreds of users concurrently.
You need to store rows that will be processed later by the stored procedure. The object that stores the rows must meet the following requirements:
✑ Be indexable
✑ Contain up-to-date statistics
✑ Be able to scale between 10 and 100,000 rows
The solution must prevent users from accessing one another’s data.
Solution: You create a table variable in the stored procedure.
Does this meet the goal?
A. Yes
B. No
B. No
Note: This question is part of a series of questions that present the same scenario. Each question in the series contains a unique solution that might meet the stated goals. Some question sets might have more than one correct solution, while others might not have a correct solution.
After you answer a question in this section, you will NOT be able to return to it. As a result, these questions will not appear in the review screen.
You are creating indexes in a data warehouse.
You have a dimension table named Table1 that has 10,000 rows. The rows are used to generate several reports.
The reports join a column that is the primary key.
The execution plan contains bookmark lookups for Table1.
You discover that the reports run slower than expected.
You need to reduce the amount of time it takes to run the reports.
Solution: You create a hash index on the primary key column.
Does this meet the goal?
A. Yes
B. No
B. No
Note: This question is part of a series of questions that present the same scenario. Each question in the series contains a unique solution that might meet the stated goals. Some question sets might have more than one correct solution, while others might not have a correct solution.
After you answer a question in this section, you will NOT be able to return to it. As a result, these questions will not appear in the review screen.
You are creating indexes in a data warehouse.
You have a dimension table named Table1 that has 10,000 rows. The rows are used to generate several reports.
The reports join a column that is the primary key.
The execution plan contains bookmark lookups for Table1.
You discover that the reports run slower than expected.
You need to reduce the amount of time it takes to run the reports.
Solution: You create a clustered index on the primary key column.
Does this meet the goal?
A. Yes
B. No
A. Yes
Box 1: All transactions are rolled back.
The first IF-statement, IF @CODE = ‘C2323’ AND @ApplicationID = 1, will be true, an error will be raised, the error will be caught in the CATCH block, and the only transaction that has been started will be rolled back.
Box 2: Only Log1, Log2, and Log3 tables are updated.
The second IF-statement, IF @Code = ‘C2323’, will be true, so the second transaction will be rolled back, but log1, log2, and log3 was updated before the second transaction.
Note: This question is part of a series of questions that present the same scenario. Each question in the series contains a unique solution that might meet the stated goals. Some question sets might have more than one correct solution, while others might not have a correct solution.
After you answer a question in this section, you will NOT be able to return to it. As a result, these questions will not appear in the review screen.
You are creating indexes in a data warehouse.
You have a dimension table named Table1 that has 10,000 rows. The rows are used to generate several reports.
The reports join a column that is the primary key.
The execution plan contains bookmark lookups for Table1.
You discover that the reports run slower than expected.
You need to reduce the amount of time it takes to run the reports.
Solution: You create a nonclustered index on the primary key column that includes the bookmark lookup columns.
Does this meet the goal?
A. Yes
B. No
B. No
Note: This question is part of a series of questions that present the same scenario. Each question in the series contains a unique solution that might meet the stated goals.
Some question sets might have more than one correct solution, while others might not have a correct solution.
After you answer a question in this section, you will NOT be able to return to it. As a result, these questions will not appear in the review screen.
You have a database named DB1 that contains two tables named Sales.Customers and Sales.Orders. Sales.Customers has a foreign key relationship to a column named
CustomerID in SalesOrders.
You need to recommend a query that returns all the customers. The query must also return the number of orders that each customer placed in 2016.
Solution: You recommend the following query:
SELECT
Cust.CustomerName,
NumberOfOrders = COUNT (*)
FROM
Sales.Customers Cust
LEFT JOIN
Sales.Orders Ord
ON Cust.CustomerID = Ord.OrderID
GROUP BY
Cust.CustomerName;
Does this meet the goal?
A. Yes
B. No
B. No
Note: This question is part of a series of questions that present the same scenario. Each question in the series contains unique solution that might meel the stated goals.
Some question sets might have more than one correct solution, while others might not have a correct solution.
After you answer a question in this section, you will NOT be able to return to it. As a result, these questions will not appear in the review screen.
You have a database named DB1 that contains two tables named Sales.Customers and Sales.Orders. Sales.Customers has a foreign key relationship to a column named
CustomerID in Sales.Orders.
You need to recommend a query that returns all the customers. The query must also return the number of orders that each customer placed in 2016.
Solution: You recommend the following query:
SELECT
Cust.CustomerName,
NumberOfOrders = COUNT (Cust.CustomerID)
FROM
Sales.Customers Cust
LEFT JOIN
Sales.Orders Ord
ON Cust CustomerID = Ord.OrderID
GROUP BY
Cust.CustomerName
Does this meet the goal?
A. Yes
B. No
A. Yes
Note: This question is part of a series of questions that present the same scenario. Each question in the series contains a unique solution that might meet the stated goals.
Some question sets might have more than one correct solution, while others might not have a correct solution.
After you answer a question in this section, you will NOT be able to return to it. As a result, these questions will not appear in the review screen.
You have a database named DB1 that contains two tables named Sales.Customers and Sales.Orders. Sales.Customers has a foreign key relationship to a column named
CustomerID in Sales. Orders.
You need to recommend a query that returns all the customers. The query must also return the number of orders that each customer placed in 2016.
Solution: You recommend the following query:
SELECT
Cust.CustomerName,
NumberofOrders = COUNT (Ord.OrderID)
FROM
Sales.Customers Cust
LEFT JOIN
Sales.Orders Ord
ON Cust.CustomerID = Ord.OrderID
GROUP BY
Cust.CustomerName;
Does this meet the goal?
A. Yes
B. No
B. No
A. Yes
A. SELECT C.CustomerID, ISNULL (MAX (OrderDate), ‘19000101’)
FROM Sales.Customer C LEFT OUTER JOIN Sales.SalesOrderHeader SOH
ON C.CustomerID = SOH.CustomerID
GROUP BY C.CustomerID
ORDER BY C.CustomerID
Correct Answer: See explanation below
- SELECT avg(P.ProductPrice) AS Average, min(P.ProductsInStock) AS LowestNumber, max(P.ProductPrice) AS HighestPrice
- FROM Sales.Products AS P
Make the additions to line 1.
Box 1: TRY”¦CATCH -
The TRY…CATCH Transact-SQL construct implements error handling for Transact-SQL that is similar to the exception handling in the Microsoft Visual C# and
Microsoft Visual C++ languages. A group of Transact-SQL statements can be enclosed in a TRY block. If an error occurs in the TRY block, control is passed to another group of statements that is enclosed in a CATCH block.
Box 2: RAISERROR(50555, 14, 1 ‘The update failed.”) WITH LOG
We must use RAISERROR to be able to specify the required severity level of 14, and we should also use the LOG option, which Logs the error in the error log and the application log for the instance of the Microsoft SQL Server Database Engine, as this enable a MS MS SQL SERVER alert to be triggered.
Note: 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.
Incorrect Answers:
Not THROW: THROW does not have a severity parameter.
You are developing a mobile app to manage meetups. The app allows for users to view the 25 closest people with similar interests. You have a table that contains records
for approximately two million people. You create the table by running the following Transact-SQL statement:
CREATE TABLE Person (
PersonID INT,
Name NVARCHAR (155) NOT NULL,
Location GEOGRAPHY,
Interests NVARCHAR (MAX)
You create the following table valued function to generate lists of people:
CREATE FUNCTION dbo.nearby (@person AS INT)
RETURNS @Res TABLE
Personid INT NOT NULL,
Location GEOGRAPHY
)
AS
BEGIN
END
You need to build a report that shows meetings with at least two people only.
What should you use?
A. OUTER APPLY
B. CROSS APPLY
C. PIVOT
D. LEFT OUTER JOIN
B. CROSS APPLY
You develop and deploy : project management application. The application uses a Microsoft SQL Server database to store data. You are developing a software bug tracking
add-on for the application.
The add-on must meet the following requirements:
¢ Allow case sensitive searches for product.
¢ Filter search results based on exact text in the description. “c Support multibyte Unicode characters.
You run the following Transact-SQL statement:
CREATE TABLE Bug (
Id UNIQUEIDENTIFIER NOT NULL,
Product NVARCHAR (255) NOT NULL,
Description NVARCHAR (max) NOT NULL,
DateCreated DATETIME NULL,
ReportingUser VARCHAR(50) NULL
You need to ensure that users can perform searches of descriptions.
Which Transact-SQL statem should you run?
A.DECLARE @term NVARCHAR(255)
SELECT Id, Description
FROM Bug
WHERE CHARINDEX(@term, Description) > 0
B. DECLARE @term NVARCHAR(255)
SELECT Id, Description
FROM Bug
WHERE DIFFERENCE (@term, Description) > 0
C. DECLARE @term NVARCHAR(255)
SELECT Id, Description
FROM Buq
WHERE CONTAINS (Description, ‘$@termt’)
D. DECLARE @term NVARCHAR(255)
SELECT Id, Description
FROM Bug
WHERE CONTAINS (Description, @term)
D. DECLARE @term NVARCHAR(255)
SELECT Id, Description
FROM Bug
WHERE CONTAINS (Description, @term)
You are building a stored procedure named SP1 that calls a stored procedure named SP2.
SP2 calls another stored procedure named SP3 that returns a Recordset. The Recordset is stored in a temporary table.
You need to ensure that SP2 returns a text value to SP1.
What should you do?
- A. Create a temporary table in SP2, and then insert the text value into the table.
- B. Return the text value by using the ReturnValue when SP2 is called.
- C. Add the txt value to an OUTPUT parameter of SP2.
- D. Create a table variable in SP2, and then insert the text value into the table.
C. Add the txt value to an OUTPUT parameter of SP2.
Note: This question is part of a series of questions that present the same scenario. Each question in the series contains a unique solution that might meet the stated goals. Some question sets might have more than one correct solution, while others might not have a correct solution.
After you answer a question in this section, you will NOT be able to return to it. As a result, these questions will not appear in the review screen.
You are creating indexes in a data warehouse.
You have a dimension table named Table1 that has 10,000 rows. The rows are used to generate several reports.
The reports join a column that is the primary key.
The execution plan contains bookmark lookups for Table1.
You discover that the reports run slower than expected.
You need to reduce the amount of time it takes to run the reports.
Solution: You create a nonclustered index on the primary key column that does NOT include columns.
Does this meet the goal?
- A. Yes
- B. No
Correct Answer: A
Note: This question is part of a series of questions that present the same scenario. Each question in the series contains a unique solution that might meet the stated goals.
Some question sets might have more than one correct solution, while others might not have a correct solution.
After you answer a question in this section, you will NOT be able to return to it. As a result, these questions will not appear in the review screen.
You create a table named Customer by running the following Transact-SQL statement:
CREATE TABLE Customer
CustomexID int IDENTITY(1,1) PRIMARY KEY,
FirstName varchar(50) NULL,
LastName varchar (50) NOT NULL,
DateOfBirth date NOT NULL,
CreditLimit money CHECK (CreditLimit 10000),
TownID int NULL REFERENCES Town (TOWNID),
CreatedDate datetime DEFAULT (GETDATE () )
You create a cursor by running the following Transact-SQL statement:
DECLARE cur CURSOR
FOR
SELECT LastName, CreditLimit
FROM Customer
DECLARE @LastName varchar (50), @CreditLimit money
OPEN cur
FETCH NEXT FROM cur INTO @LastName, @CreditLimit
WHILE (@@FETCH_STATUS = 0)
BEGIN
FETCH NEXT FROM cur INTO @LastName, @CreditLimit
END
CLOSE cur
DEALLOCATE cur
the credit limit is zero, you must delete the customer record while fetching data.
You need to add the DELETE statement.
Solution: You add the following Transact-SQL statement:
IF @CreditLimit = 0
DELETE Customer
WHERE CustomerID IN (SELECT CustomerID)
FROM Customer WHERE LastName = @LastName)
Does the solution meet the goal?
A. Yes
B. No
Correct Answer: B
Use a WHERE CURRENT OF clause, which deletes at the current position of the specified cursor.
Note: This question is part of a series of questions that present the same scenario. Each question in the series contains a unique solution that might meet the stated goals.
Some question sets might have more than one correct solution, while others might not have a correct solution.
After you answer a question in this section, you will NOT be able to return to it. As a result, these questions will not appear in the review screen.
You create a table named Customer by running the following Transact-SQL statement:
CREATE TABLE Customer
CustomerID int IDENTITY(1,1) PRIMARY KEY,
FirstName varchar(50) NULL,
LastName varchar(50) NOT NULL,
DateOfBirth date NOT NULL,
CreditLimit money CHECK (CreditLimit < 10000),
TownID int NULL REFERENCES Town (TOWnID),
CreatedDate datetime DEFAULT (GETDATE () )
You create a cursor by running the following Transact-SQL statement:
DECLARE cur CURSOR
FOR
SELECT LastName, CreditLimit
FROM Customer
DECLARE @LastName varchar(50), @CreditLimit money
OPEN cur
FETCH NEXT FROM cur INTO @LastName, @CreditLimit
WHILE (@@FETCH_STATUS = 0)
BEGIN
FETCH NEXT FROM cur INTO @LastName, @CreditLimit
END
CLOSE cur
DEALLOCATE cur
If the credit limit is zero, you must delete the customer record while fetching data.
You need to add the DELETE statement.
Solution: You add the following Transact-SQL statement:
IF @CreditLimit = 0
DELETE Customer
WHERE CURRENT OF cur
Does the solution meet the goal?
A. Yes
B. No
Correct Answer: A
CURRENT OF specifies that the DELETE is performed at the current position of the specified cursor.