Quantcast
Channel: Questions in topic: "syntax"
Viewing all 57 articles
Browse latest View live

UDF syntax

$
0
0
Hi, Please, can someone help me check my syntax below for UDF; -- ============================================= -- Author: -- Create date: 08/10/2017 -- Description: Used to get the UserLoginID using BusinessEntityId Parameter -- ============================================= --1) Create a UDF that accepts EmployeeID(2012,; BusinessEntityID) and returns UserLoginID. The UserLoginID is the last part of the --LoginID column. Its only the partthat comes after '\' CREATE FUNCTION Fx_GetUserLoginID ( @BusinessEntityID int -- Add the parameters for the function here ) RETURNS int AS BEGIN DECLARE @BusinessEntityID int -- Declare the return variable here SELECT RIGHT(loginID, LEN(LoginID) - CHARINDEX('\', Login)) AS UserLoginID --Add the T-SQL statements to compute the return value here FROM HumanResources.Employee WHERE BusinessEntityID = @BusinessEntityID -- Return the result of the function RETURN UserLoginID END GO --2) Create a UDF that accepts EmployeeID (2012: BusinessEntityID) and returns their age. -- ============================================= -- Author: -- Create date: 08/10/2017 -- Description: Used to get the Employee Age using BusinessEntityID(EmployeeID) parameter. -- ============================================= SELECT DATEDIFF(YY, BirthDate, GETDATE()) AS Age FROM HumanResources.Employee WHERE BusinessEntityID = @BusinessEntityID CREATE FUNCTION Fx_GetAgeByBusinessEntityID ( @BusinessEntityID int ) RETURNS int AS BEGIN -- Declare the return variable here DECLARE @BusinessEntityID int SELECT DATEDIFF(YY, BirthDate, GETDATE()) AS Age FROM HumanResources.Employee WHERE BusinessEntityID = @BusinessEntityID -- Return the result of the function RETURN Age END GO --3) Create a UDF that accepts the Gender and returns the average vacationHours -- ============================================= -- Author: -- Create date: 08/10/2017 -- Description: Used to get Average Employees VacationHours using the Gender parameter -- ============================================= CREATE FUNCTION Fx_GetVacationHrUsingGender ( @Gender bit ) RETURNS TABLE ( BusinessEntityID int, VacationHours int ) AS BEGIN ( SELECT AVG(VacationHours) AS AvgVacationHrs FROM HumanResources.Employee WHERE Gender = @Gender ) RETURN AvgVacationHrs END GO --4)Create a UDF that accepts ManagerID(2012: Jobtitle) and returns all of that ManagerID(2012: JobTitle) Employee Information. --a) LoginID -- ============================================= -- Author: Gabriel Ehima -- Create date: -- Description: Used to get Manager's Employee's Information by using LoginID parameter -- ============================================= CREATE FUNCTION GetMgrEmployeeInfo ( @LoginID int ) RETURNS TABLE ( -- Add the column definitions for the TABLE variable here , ) AS BEGIN SELECT * AS MgrEmployeeInfo FROM HumanResources.Employee WHERE Title Like '%Manager%' AND LoginID = @LoginID RETURN MgrEmployeeInfo END GO --4)Create a UDF that accepts ManagerID(2012: Jobtitle) and returns all of that ManagerID(2012: JobTitle) Employee Information. --b) Gender -- ============================================= -- Author: -- Create date: 08/10/2017 -- Description: Used to get Manager's Employee's Information by using Gender parameter -- ============================================= CREATE FUNCTION GetMgrEmployeeInfo ( Gender bit ) RETURNS TABLE ( -- Add the column definitions for the TABLE variable here , ) AS BEGIN SELECT * FROM HumanResources.Employee WHERE Title Like '%Manager%' AND Gender = @Gender RETURN MgrEmployeeInfo END GO --4)Create a UDF that accepts ManagerID(2012: Jobtitle) and returns all of that ManagerID(2012: JobTitle) Employee Information. --c) HireDate -- ============================================= -- Author: -- Create date: 08/10/2017 -- Description: Used to get Manager's Employee's Information by using HireDate parameter -- ============================================= CREATE FUNCTION GetMgrEmployeeInfo ( HireDate datetime ) RETURNS TABLE ( -- Add the column definitions for the TABLE variable here , ) AS BEGIN SELECT * FROM HumanResources.Employee WHERE Title Like '%Manager%' AND HireDate = @HireDate RETURN MgrEmployeeInfo END GO /* Scalar function CREATE FUNCTION ( -- Add the parameters for the function here <@Param1, sysname, @p1> ) RETURNS AS BEGIN -- Declare the return variable here DECLARE <@ResultVar, sysname, @Result> -- Add the T-SQL statements to compute the return value here SELECT <@ResultVar, sysname, @Result> = <@Param1, sysname, @p1> -- Return the result of the function RETURN <@ResultVar, sysname, @Result> END GO Table Function -- ============================================= -- Author: -- Create date: 08/10/2017 -- Description: -- ============================================= CREATE FUNCTION ( -- Add the parameters for the function here<@param1, sysname, @p1>,<@param2, sysname, @p2> ) RETURNS<@Table_Variable_Name, sysname, @Table_Var> TABLE ( -- Add the column definitions for the TABLE variable here, ) AS BEGIN -- Fill the table variable with the rows for your result set RETURN END GO */

Join Syntax

$
0
0
Hi, Can some check this join syntax and see if its correct; CREATE TABLE Emp ( EmpID int, EmpName varchar(50), DeptID int, StartDate datetime, Salary money, LocationID int, EmpStatus int ) CREATE TABLE Location ( LocationID int, Adrress1 varchar(50), Address2 varchar(50), City varchar(50), State VARCHAR(50) ) CREATE TABLE Dept ( DeptID int, DeptName varchar(50) ) -- Write a Tsql query joining all three tables emp e, dept d, location l --INNER JOIN SELECT e.EmpID, e.EmpName, e.DeptID, e.LocationID, d.DeptName, l.City, l.State FROM Emp e INNER JOIN Dept d ON d.DeptID = e.DeptID INNER JOIN Location l ON e.LocationID = l.LocationID --left outer join SELECT e.[EmpID], e.[EmpName], e.[Salary], e.DeptID, d.DeptName FROM Dept d LEFT OUTER JOIN Emp e ON e.DeptID = d.DeptID --Right Outer Join SELECT e.EmpID, e.EmpName, d.DeptID, d.DeptName FROM Dept d RIGHT OUTER JOIN Emp e ON d.DeptID = E.DeptID CREATE TABLE Stg_Emp ( EmpID int, Empname varchar(50) ) INSERT INTO Stg_Emp(EmpID, Empname) VALUES (1, 'John Doe'), (2, 'Jane Doe'), (3, 'Sally Mae') CREATE TABLE Emp_List ( EmpID int, EmpName varchar(50) ) INSERT INTO Emp_List (EmpID, EmpName) VALUES (1, 'John Doe'), (2, 'Jane Doe'), (5, 'Peggy Sue') --1) The stg_Emp table contains all new and current employees --2) The Emp_List tablecontains some current and all former employee Stg_Emp = s, Emp_List = e --1) Show company new employee SELECT s.EmpID, s.EmpName, e.EmpName FROM Stg_Emp s LEFT OUTER JOIN Emp_List e ON s.EmpID=e.EmpID --2) Show company former employee SELECT s.EmpID, s.EmpName, e.EmpName FROM Stg_Emp s RIGHT OUTER JOIN Emp_List e ON s.EmpID=e.EmpID

JOIN UDF SYNTAX

$
0
0
--2) How many sales orders (Headers) used Vista credit cards in October 2012 select * FROM [Sales].[SalesOrderHeader] H select * from [Sales].[CreditCard] where year([ModifiedDate]) = 2007 S SELECT h.SalesOrderID, h.[CreditCardID], s.[CardType] FROM [Sales].[SalesOrderHeader] h JOIN [Sales].[CreditCard] s ON s.CreditCardID = h.CreditCardID WHERE [CardType] = 'Vista' AND s.ModifiedDate BETWEEN '2012-10-01' AND '2012-10-31' --3) --4) Create UDF that accepts start date and end date. The function will return the number of sales (using vista credit cards) that took place --between the start date and end date entered by the user --SELECT COUNT (*) AS CountOfSales --FROM [Sales].[SalesOrderHeader] h --JOIN [Sales].[CreditCard] s --ON s.CreditCardID = h.CreditCardID --WHERE [CardType] = 'Vista' --AND s.ModifiedDate BETWEEN '2007-01-01' AND '2007-10-31'; CREATE FUNCTION dbo.Fx_CountOfSales ( @Startdate datetime, @EndDate datetime ) RETURNS int AS BEGIN DECLARE @Fx_CountOfSales AS int SET @Fx_CountOfSales = ( SELECT COUNT (*) AS CountOfSales FROM [Sales].[SalesOrderHeader] h JOIN [Sales].[CreditCard] s ON s.CreditCardID = h.CreditCardID WHERE [CardType] = 'Vista' AND s.ModifiedDate BETWEEN '2007-01-01' AND '2007-10-31' ) RETURN @Fx_CountOfSales END --5) Using the SalesOrderHeader table- Find out how much revenue (TotalDue) was brought in by the North American Territory Group from 2002 --through 2004 select * FROM [AdventureWorks2008R2].[Sales].[CreditCard] SELECT [TotalDue] FROM [Sales].[SalesOrderHeader] WHERE TerritoryID IN (1,2,3,4,5,6) --AND [OrderDate] BETWEEN 2005-01-01 AND 2007-12-31 ORDER BY ModifiedDate select * from [Sales].[SalesTerritory] s SELECT h.[TotalDue] FROM [Sales].[SalesOrderHeader] h INNER JOIN [Sales].[SalesTerritory] s ON h.[TerritoryID] = s.TerritoryID WHERE h.TerritoryID IN (1,2,3,4,5,6) AND h.[OrderDate] BETWEEN YEAR(2005) AND YEAR(2007) --6) What is the sales taxrate, StateProvinceCode and CountryRegionCode for Texas SELECT * FROM [Sales].[SalesTaxRate] SELECT * FROM [Sales].[SalesTerritory] t ORDER BY ModifiedDate select * from [Sales].[SalesTaxRate] s SELECT s.[TaxRate], s.[StateProvinceID], t.[CountryRegionCode] FROM [Sales].[SalesTaxRate] s JOIN [Sales].[SalesTerritory] t ON s.[ModifiedDate] = t.[ModifiedDate] WHERE s.[Name] Like 'Texas%' --7) Store the information from Q5 in a variable DECLARE @GrandTotalDue MONEY SET @GrandTotalDue = ( SELECT h.[TotalDue] FROM [Sales].[SalesOrderHeader] h INNER JOIN [Sales].[SalesTerritory] s ON h.[TerritoryID] = s.TerritoryID WHERE h.TerritoryID IN (1,2,3,4,5,6) AND h.[OrderDate] BETWEEN YEAR(2005) AND YEAR(2007) ) SELECT @GrandTotalDue as GrandTotal --8) Create A UDF that accepts the State Province and returns the associated sales taxrate. StateProvince Code and Country Region Code CREATE FUNCTION Fx_Utility ( @StateProvinceID int ) RETURNS TABLE AS RETURN ( SELECT s.[TaxRate], s.[StateProvinceID], t.[CountryRegionCode] FROM [Sales].[SalesTaxRate] s JOIN [Sales].[SalesTerritory] t ON s.[ModifiedDate] = t.[ModifiedDate] WHERE s.[Name] Like '%@State%' ) SELECT * FROM Fx_Utility('California') --9) Show a list of Product Colors. For each color show how many sales details there are and the total sales Amount(Unit*OrderQty) --Only show colors with a Total Sales Amount more than 50,000.00 and eliminate the product that do not have a color; --SELECT * --FROM [Production].[Product] p --SELECT * --FROM [Sales].[SalesOrderDetail] s SELECT DISTINCT(p.color) AS Color, COUNT(s.SalesOrderID) AS OrderID, SUM(s.[UnitPrice]*s.OrderQty) AS TotalSalesAmt FROM [Sales].[SalesOrderDetail] S JOIN [Production].[Product] p ON s.[ProductID] = p.[ProductID] WHERE p.Color IS NOT NULL GROUP BY (p.color) HAVING SUM(s.[UnitPrice]*s.OrderQty) > 50000

four table join syntax

$
0
0
Hey Everyone, Please, check out the four table join query and see if it correct --Get SalesOrderID, CustomerID, TerritoryID and TotalDue for highest amount ordered in 2007 SELECT h.[SalesOrderID], c.[CustomerID], t.[TerritoryID], s.[CardNumber] FROM [Sales].[SalesOrderHeader] h LEFT JOIN [Sales].[Customer] c ON h.[CustomerID] = c.[CustomerID] LEFT JOIN [Sales].[SalesTerritory] t ON h.[TerritoryID] = t.TerritoryID LEFT JOIN [Sales].[CreditCard] s ON h.[CreditCardID] = s.CreditCardID WHERE [TotalDue] = (SELECT max([TotalDue]) FROM [Sales].[SalesOrderHeader] WHERE YEAR([OrderDate]) = 2007) --joined these four tables to display SalesOrderID, CustomerID, TerritoryID and credit card number for highest amount ordered in 2007 --The [Sales].[SalesOrderHeader] is the main table that has CustomerID, TerritoryID, CreditCardID as foreign key on the table. --CustomerId column is a foreign key in the [Sales].[SalesOrderHeader] table is used to join CustomerId column which is a primary in --[Sales].[Customer] table. --TerritoryID column is a foreign key in the [Sales].[SalesOrderHeader] table is used to join TerritoryID column which is a primary in --[Sales].[SalesTerritory] table. --CreditCardID column is a foreign key in the [Sales].[SalesOrderHeader] table is used to join TerritoryID column which is a primary in --[Sales].[CreditCard] table and the credit card number is retrieved from this table to the result set.

Four Table Join Syntax

$
0
0
--Get SalesOrderID, CustomerID, TerritoryID and TotalDue for highest amount ordered in 2007 Question: Get SalesOrderID, CustomerID, TerritoryID and TotalDue for highest amount ordered in 2007 SELECT h.[SalesOrderID], c.[CustomerID], t.[TerritoryID], s.[CardNumber] FROM [Sales].[SalesOrderHeader] h LEFT JOIN [Sales].[Customer] c ON h.[CustomerID] = c.[CustomerID] LEFT JOIN [Sales].[SalesTerritory] t ON h.[TerritoryID] = t.TerritoryID LEFT JOIN [Sales].[CreditCard] s ON h.[CreditCardID] = s.CreditCardID WHERE [TotalDue] = (SELECT max([TotalDue]) FROM [Sales].[SalesOrderHeader] WHERE YEAR([OrderDate]) = 2007) The [Sales].[SalesOrderHeader] is the main table that has CustomerID, TerritoryID, CreditCardID as foreign keys on the table. The SalesOrderID is retrieved from here to join the result set. CustomerId column is a foreign key in the [Sales].[SalesOrderHeader] table is used to join CustomerId column which is a primary in [Sales].[Customer] table. The CustomerID is retrieved from here to join the result set. TerritoryID column is a foreign key in the [Sales].[SalesOrderHeader] table is used to join TerritoryID column which is a primary in [Sales].[SalesTerritory] table. The TerritoryID is retrieved from here to join the result set. CreditCardID column is a foreign key in the [Sales].[SalesOrderHeader] table is used to join CreditCardID column which is a primary in [Sales].[CreditCard] table and the credit card number is retrieved from this table to the result set.    

query syntax

$
0
0
Hi, can someone help check my syntax if they are correct. Thx --1) What does the acrocyn T-SQL stands for? Transact-Structured Query Language --2) What keyword in a SQL query do you use to extract data from a database? SELECT --3) What keyword in a SQL query do you use to modify data from a database table? UPDATE --4) What keyword in a SQL query do you use to add data from a database table? INSERT --5)What is the difference between the following Joins? a) Left Join performs a join starting with the first(leftmost) table and then any matching second (right-most) table records. b) Inner Join returns rows when there is a match in both tables c) Right Join performs a join starting with the second (right most) table amd then any matching first(left-most) table records. --6)What is the differnce between a table and a view A table is a physical object in the database while a view is a logical object in the database. A table contains data, a view is just a SELECT statement which has been saved in the database (more or less, depending on your database). The advantage of a view is that it can join data from several tables thus creating a new view of it. --7) What is the difference between a temporary and variable table Both Temporary Tables (a.k.a #Tables) and Table Variables (a.k.a @Tables) in Sql Server provide a mechanism for Temporary holding/storage of the result-set for further processing. 1)Temp tables are created in tempdb. They act like regular table in that you can query their data via SELECT and modify their data via UPDATE, INSERT and DELETE statements. Table variable is created in memory and cannot be modified nor can we explicitly drop it. 2)Temp tables honor the explicit transactions defined by the user. Table variable does not participate in the explicit transactions defined by the user. 3)Temp tables are not allowed in User Defined Functions. Table variables can be used in UDF. 4)Temp tables support adding indexes explicitly after Temp table creation and it can also have the implicit indexes. Table variable do not allow explicit creation of indexs after its declaration, the only way implicit indexes are created is during declaration of table. 5)Temp tables records transaction logs while Table variables transactions are not logged. 6)Stored procedure with a temporary table cannot be pre-compiled, while an execution plan of procedures with table variables can be statically compiled in advance. Pre-compiling a script gives a major advantage to its speed of execution. This advantage can be dramatic for long procedures, where recompilation can be too pricy. 7)Finally, table variables exist only in the same scope as variables. Contrary to the temporary tables, they are not visible in inner stored procedures and in exec(string) statements. Also, they cannot be used in an insert/exec statement. --8) Create two tables and answer the questions below USE [TestDemo] DROP TABLE TABLEA CREATE TABLE TABLEA ( Field1 int ) INSERT INTO TABLEA (Field1) VALUES (1), (2), (3), (4), (4), (5), (6) DROP TABLE TABLEB CREATE TABLE TABLEB ( Field1 int ) INSERT INTO TABLEB(Field1) VALUES (2), (5), (7), (6), (3), (3), (9) --8) Display data from TableA where the values are identical in TableB SELECT a.* FROM [dbo].[TABLEA] a INNER JOIN [dbo].[TABLEB] b ON a.Field1 = b.Field1 select * from TABLEA select * from TABLEB --9) Display data from TableA where the values are not available in TableB SELECT a.* FROM [dbo].[TABLEB] b RIGHT OUTER JOIN [dbo].[TABLEA] a ON a.Field1 = b.Field1 --10) Display data from TableB where the values are not in TableA SELECT b.* FROM [dbo].[TABLEB] b RIGHT OUTER JOIN [dbo].[TABLEA] a ON a.Field1 = b.Field1 select * from TABLEA select * from TABLEB --11) Display Unique values from TableA SELECT DISTINCT * FROM [dbo].[TABLEA] --12) Display the total number of records, per unique value in TableA SELECT DISTINCT COUNT(*) AS DistinctCount FROM [dbo].[TABLEA] --13) Display the unique value from TableB where it occurs more than once SELECT COUNT(*) AS NoOfCount, [Field1] FROM [dbo].[TABLEB] GROUP BY [Field1] HAVING COUNT(*) > 1 --14) Display the greatest value from TableB SELECT MAX([Field1]) AS LargestValue FROM [dbo].[TABLEB] GO --15) Display the small value from tablA SELECT MIN([Field1]) AS SmallestValue FROM [dbo].[TABLEA] select * from TABLEA select * from TABLEB --16) Write a SQl statement to create a variable called Variable1 that can handle the value such as "Welcome to planet earth" DECLARE @Variable1 char(50) SET @Variable1 = 'Welcome to planet earth' SELECT @Variable1 AS Message --17) Write a SQl statement that constructs a table called Table1 with the following fields; a) Field1 --this field stores number such as 1,2,3 etc b) Field2 --this field stores the date and time c) Field3 - this field stores the text up to 500 characters CREATE TABLE Table1 ( Field1 int, Field2 datetime, Field3 varchar(500) ) --18)Write a SQL statement that adds the following records to Table1; INSERT INTO Table1(Field1, Field2, Field3) VALUES (34, '1/19/2012 08:00AM', 'Mars Saturn'), (65, '02/15/2012 10:30am', 'Big Bright Sun'), (89, '3/31/2012', 'Red Hot Mercury') select * from Table1 --19) Write a SQL statement to change the value for Field3 in Table1 to the value stored in Variable1(From question 16), on the record that is 34 DECLARE @Variable1 char(50) SET @Variable1 = ( SELECT CAST([Field3] AS varchar(500)) FROM [dbo].[Table1] WHERE [Field1] = 34 ) SELECT @Variable1 AS Message --20) Write a SQL statement for record 89 to return the total number of character for field3 SELECT LEN([Field3]) AS Characterlenght FROM [dbo].[Table1] WHERE [Field1] = 89 --21) Write a SQL statement for record 65 to return the first occurence of a space in Field3 SELECT CHARINDEX(' ', [Field3]) FROM [dbo].[Table1] WHERE [Field1] = 65 --22) Write a SQl statement for record 65 to return the value "Bright" from field3 SELECT SUBSTRING('Big Bright Sun', 5, 6) FROM [dbo].[Table1] WHERE [Field1] = 65 --23) Write a SQL statement for record 34 to return the day from the Field2 SELECT DATEPART(DD, [Field2]) FROM [dbo].[Table1] WHERE [Field1] = 34 --24) Write a SQL statement for record 34 to return the first day of the month from field2 SELECT DATEADD(MM, DATEDIFF(MM,0, [Field2]), 0) FROM [dbo].[Table1] WHERE [Field1] = 34 --25) Write a SQL statement for record 34 to return the previous end of the month from field2 SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,[Field2]),0)) FROM [dbo].[Table1] WHERE [Field1] = 34 --26) Write a SQL statement for record 34 to return the day of the week from the field2 SELECT DATENAME(DW, [Field2]) AS WEEKDAY FROM [dbo].[Table1] WHERE [Field1] = 34 --27) Write a SQL statement for record 34 to return the date as CCYYMMDD from field2 SELECT CONVERT(char(8), [Field2], 112) FROM [dbo].[Table1] WHERE [Field1] = 34 --28) Write a SQL statement to add a new column, Field 4(datatype can be of any preference) to Table1 ALTER TABLE [dbo].[Table1] ADD Field4 varchar(50) --29) Write SQl statement to remove record 65 from Table1 DELETE [dbo].[Table1] WHERE [Field1] = 65 SELECT * FROM Table1 --30)Write a SQL statement to wipe all records in Table1 DELETE [dbo].[Table1] ---)Write a SQL statement to rem

View Syntax

$
0
0
CREATE VIEW Vw_Curriculum as SELECT P.PathID, P.PathName, P.PathDesc, P.PathActive, P.InsertDate, P.PathOrderID, P.PrePath, P.PrePathID, P.PathLongDesc, P.PathLength, P.PathCost, P.PathNeededMaterials, c.CourseID, c.CourseName, c.CourseOrder, c.CourseDesc, c.CourseActive, s.SectionID, s.SectionName, s.SectionOrder, s.SectionDesc, s.RoleID, s.SectionActive, s.EventCount, e.EventID, e.EventName, e.DocumentID, e.EventOrder, e.EventActive, e.Repeat, t.EventTypeID, t.EventTypeName, d.DocumentName, d.DocumentDesc, d.DocumentLink, d.IsAttached, d.IsActive FROM [dbo].[Path] P LEFT OUTER JOIN [dbo].[Course] c ON P.PathID = C.PathID LEFT OUTER JOIN [dbo].[Section] s ON c.CourseID = s.CourseID LEFT OUTER JOIN [dbo].[ADF_Event] e ON s.SectionID = e.SectionID LEFT OUTER JOIN [dbo].[ADF_EventType] t ON t.[EventTypeID] = e.[EventID] LEFT OUTER JOIN [dbo].[ADF_Document] d ON t.[EventTypeID] = d.[EventTypeID]

Incorrect syntax near BEER

$
0
0
Hi, I have a link server from SQL connect to AS400 configured to run OPENQUERY to retrieve data from AS400. I encountered "Incorrect syntax near BEER" syntax error from SQL SSMS. I can't figure out why this simply condition would give me an error. If I remove the WHERE DEPARTMENT = ''BEER'' condition, it retrieve data from AS400 with success. Does anyone know how to correct below syntax error? SELECT * FROM OPENQUERY(AS400,' SELECT DEPARTMENT, CLASS FROM MYLIB.WORKTBL01 WHERE DATE = 20171217 AND DEPARTMENT = ''BEER'' ') Msg 102, Level 15, State 1, Line 7 Incorrect syntax near 'BEER'.

What is the colon used for in T-SQL

$
0
0
I accidently created a query like this: Hello: SELECT * FROM TableA To my surprise, there were no syntax errors. Can someone tell me why the Hello: did not cause a syntax error? I searched the web and couldn't find an answer.

Stored Procedure Syntax

$
0
0
Hi, I have this stored procedure which was sent to me by a colleague. The stored procedure is supposed to automate table archiving in SQL Server. The problem I was having when reading the SP is that in the section where we assigned SET @CutOffSQL below; where @CutOffDate = The cut off date, generated by using DATEADD with the @CutOffInterval and @CutOffType parameters @CutOffSQL = N'SELECT @CutOffDate SET @CutOffSQL = N'SELECT @CutOffDate = CONVERT(varchar(20), DATEADD(' + @CutOffType + ', -ABS(' + CAST(@CutOffInterval AS nvarchar(10)) + '), GETDATE()),100)' This is the part I am getting confused. Can someone help check if there is an error with this part of the query. Below is the Stored Procedure and comments about the SP. ------------------------------------------------------------------------------------------------------------------------------------------------ Stored Procedure dbo.ArchiveData Description: This stored procedure dynamically creates a SQL statement to archive data from a production table to an archive table. This assumes that the structure of the source and destination tables are identical. The SQL statement is constructed by retrieving the column list for the tables from syscolumns (excluding computed columns). The columns are then appended into a single string via a cursor over the columns result set. This string isused to create a SQL statement in the following format: SET TRANSACTION ISOLATION LEVEL SERIALIZABLE BEGIN TRANSACTION INSERT INTO () SELECT FROM WHERE < DELETE FROM WHERE < IF @@ERROR = 0 BEGIN COMMIT TRANSACTION END ELSE BEGIN ROLLBACK TRANSACTION END The generated SQL string is then executed via sp_executesql. The procedure requires the following input parameters: @SourceTable sysname - This is the table the data is archived from @DestinationTable sysname - This is the table where the data is archived to @CutOffInterval int - The number of days/months/years used to determine which records to archive @CutOffType varchar(4) - The type of value specified in the @CutOffInterval variable. This must be a valid date part value for the DATEADD funtion (yy,m,d, etc) @DateColumnName sysname - This is the name of the datetime column in the source table used to determine which records are archived. All records with a value in this column less than the datetime calculated by the @CutOffInterval and @CutOffType variables will be archived. @PrintOnly bit - Indicates the procedure should generate and print the SQL commands to archive but not actually execute them. Useful if you want to customize the commands. Note that the default on this parameter is 1, so explicitly set to 0, this proc will only print the SQL command, it will not execute it. */ CREATE PROCEDURE dbo.ArchiveData ( @SourceTable sysname, @DestinationTable sysname, @CutOffInterval int, @CutOffType varchar(4), @DateColumnName sysname, @PrintOnly bit = 1 ) AS DECLARE @SQL nvarchar(4000) -- The SQL commands that will be executes DECLARE @ColumnList varchar(4000) -- The list of columns in the source and destination tables DECLARE @Column sysname -- The current column in the cursor loop DECLARE @CRLF nvarchar(20) -- CRLF to make the generated SQL look pretty when it's printed DECLARE @CutOffSQL nvarchar(500) -- Holds a SQL command that generates the cut off date DECLARE @CutOffSQLParamList nvarchar(100) -- The parameter list passed into sp_executesql when generating the cut off date time DECLARE @CutOffDate nvarchar(20) -- The cut off date, generated by using DATEADD with the @CutOffInterval and @CutOffType parameters -- First we build a SQL string that when executed, will give us a datetime to use as the cut off, to determine which records are archived SET @CutOffSQL = N'SELECT @CutOffDate = CONVERT(varchar(20), DATEADD(' + @CutOffType + ', -ABS(' + CAST(@CutOffInterval AS nvarchar(10)) + '), GETDATE()),100)' SET @CutOffSQLParamList = N'@CutOffDate nvarchar(20) OUTPUT' EXEC sp_executesql @CutOffSQL, @CutOffSQLParamList, @CutOffDate OUTPUT SET @CRLF = CHAR(13) + CHAR(10) SET @ColumnList = '' -- Now we get a cursor of all columns in the source table, excluding computed colums DECLARE column_cursor CURSOR FAST_FORWARD FOR SELECT SC.name FROM syscolumns SC INNER JOIN sysobjects SO ON SC.id = SO.id WHERE ((SO.name = @SourceTable) AND (SC.iscomputed = 0)) ORDER BY SC.colorder OPEN column_cursor -- Next we loop through the cursor and create a list of columns that will be used in the INSERT and SELECT statements FETCH NEXT FROM column_cursor INTO @Column WHILE @@FETCH_STATUS = 0 BEGIN SET @ColumnList = @ColumnList + QUOTENAME(@Column) + ',' FETCH NEXT FROM column_cursor INTO @Column END CLOSE column_cursor DEALLOCATE column_cursor -- Clean up the trailing comma on the column list SET @ColumnList = SUBSTRING (@ColumnList,1,LEN(@ColumnList) - 1) -- And now we build the SQL commands, complete with transaction handling SET @SQL = 'SET TRANSACTION ISOLATION LEVEL SERIALIZABLE' + @CRLF SET @SQL = @SQL + 'BEGIN TRANSACTION' + @CRLF SET @SQL = @SQL + 'INSERT INTO ' + @DestinationTable + ' (' + @ColumnList + ')' + @CRLF SET @SQL = @SQL + 'SELECT ' + @ColumnList + @CRLF SET @SQL = @SQL + 'FROM ' + @SourceTable + @CRLF SET @SQL = @SQL + 'WHERE ' + @DateColumnName + ' < ''' + @CutOffDate + '''' + @CRLF SET @SQL = @SQL + 'DELETE FROM ' + @SourceTable + @CRLF SET @SQL = @SQL + 'WHERE ' + @DateColumnName + ' < ''' + @CutOffDate + '''' + @CRLF SET @SQL = @SQL + 'IF @@ERROR = 0' + @CRLF SET @SQL = @SQL + ' BEGIN' + @CRLF SET @SQL = @SQL + ' COMMIT TRANSACTION' + @CRLF SET @SQL = @SQL + ' END' + @CRLF SET @SQL = @SQL + 'ELSE' + @CRLF SET @SQL = @SQL + ' BEGIN' + @CRLF SET @SQL = @SQL + ' ROLLBACK TRANSACTION' + @CRLF SET @SQL = @SQL + ' END' + @CRLF PRINT @SQL -- And finally, If @PrintOnly = 0, we execute the commands, otherwise the command string -- will just be printed IF @PrintOnly = 0 BEGIN EXEC sp_executesql @SQL END GO SET QUOTED_IDENTIFIER OFF GO SET ANSI_NULLS ON GO

When I type the word, "LOG ON" I am getting an Incorrect Syntax message, Msg 156, Level 15, State 1, Line 3, LOG On, Keyword 'On'

$
0
0
Hi, I'm taking a Udemy Course and trying to complete an exercise. I'm getting an Incorrect Syntax message, "Msg 156, Level 15, State 1, Line 3, Incorrect syntax near the keyword 'ON' when I type the command, LOG ON. I am using SQL 2012 Server Management Studio. Please advise and thanks for your assistance. Kelly Buchanan, Orlando, Florida ![alt text][1] [1]: /storage/temp/4613-msg-156-level-15-state-1-line-3.jpg

Need to fetch all the records of the student with respect to teacher id . I'm finding syntax error in this code please help me. MYsql phpadmin mariadb version.

$
0
0

DELIMITER $ CREATE PROCEDURE `sp_getstudentdetails_testQ`(IN `teacher_id` INT(15), IN `student_name` VARCHAR(30), IN `student_grades` VARCHAR(5), IN `student_status` VARCHAR(15), IN `Engagement_range` VARCHAR(30)) BEGIN select u.name as studentname,u.id as studentid,u.profile as studentprofile,u.createdby as createdby,u.createdon as createdon, u.updatedby as updatedby,u.updatedon as updatedon,u.flag_status as flagstatus,u.form_status as formstatus,s.schoolname as schoolname,s.id as schoolid,schm.idnteacher as teacherid,ud.grade from user as u left join student_class_hour_map as schm on u.id = schm.idnstudent left join school_student_rel as ssr on ssr.student_id = schm.idnstudent left join school as s on s.id = ssr.school_id LEFT join user_details as ud on u.id = ud.user_id where profile = 5 and schm.idnteacher = teacher_id and u.name like CONCAT('%',student_name,'%') AND IF(student_grades != '',FIND_IN_SET(ud.grade,student_grades),1); IF student_status != '' THEN IF student_status ='2' THEN (u.status=2 OR u.form_status<=2); ELSE FIND_IN_SET(u.flagstatus,student_status); END IF; END IF; END IF; End $$ DELIMITER;

I want to show attached file in report: -- Attachments attach.AttachmentID AS AttachID, attach.Language AS AttachLanguage, attach.FileName AS AttachFileName

$
0
0

I keep getting an incorrect syntax error attach.AttachmentID

'FORCE_LEGACY_CARDINALITY_ESTIMATION' hint in view

$
0
0

We need to add the

'FORCE_LEGACY_CARDINALITY_ESTIMATION' option to a view. When we run the select with the option clause

OPTION (USE HINT('FORCE_LEGACY_CARDINALITY_ESTIMATION'))

in SSMS, it works. When we try to alter the view with the option clause, it errors with

Incorrect syntax near the keyword 'OPTION' and

USE database statement is not allowed in a procedure, function or trigger.

How do we put the option hint in a view?

Syntax question for an 'EXEC () AT' query

$
0
0

I have the following query but I can't figure out the correct syntax to output the query result as a variable?

The query returns a record count on the Projects.dbo.Reports table on the linked server.

Any help would be greatly appreciated. Thanks Peter

EXEC ('Use Projects;

SELECT

SUM(p.row_count)

FROM sys.dm_db_partition_stats p

JOIN sys.objects o ON o.object_id = p.object_id

JOIN sys.schemas s ON o.schema_id = s.schema_id

WHERE p.index_id <2 AND o.type = ''U''

AND s.name = ''dbo''

AND o.name = ''Reports''

'

)AT [RemoteServer]


SQL Server 2005 UDF completes with an error

$
0
0

Greetings,

I am new to this and just wrote my first ever table valued UDF for SQL server 2005. When I run the query:

SELECT 
	[Tenant Id], 
	[Tenant Name], 
	[Billed], 
	[Description] 
FROM 
	DLS_tenant_bill(12345, '1-nov-2019', '1-dec-2019', 100) 
ORDER BY 
	[Tenant Id], 
	[ORDER]

it returns all rows as requested but completes with an error:

	Msg 102, Level 15, State 1, Line 9223372036854775807
	Incorrect syntax near '1'.
	Msg 102, Level 15, State 1, Line 9223372036854775807
	Incorrect syntax near '1'.
	Command completed successfully. (6125 results).

I would greatly appreciate any help in trying to figure this out. Many thanks.

i need to convert a pivot query from access to sql but can't get the syntax right please help?

$
0
0
TRANSFORM First(Val([PartData])) AS Expr1 
SELECT 
 a_tblParts.CarID
FROM 
 a_tblParts 
  INNER JOIN a_tblPartHead 
   ON a_tblParts.PartID = a_tblPartHead.PartID
WHERE 
 (((a_tblPartHead.Part) In 
  ("GA ","Legal","GV","LRating","Rear","Legal A","GC","Legal D")))
GROUP BY 
 a_tblParts.CarID
PIVOT 
 a_tblPartHead.Part;
Viewing all 57 articles
Browse latest View live


Latest Images