SQL: All the suggested GetDate () methods are not working - sql-server

I'm doing an assignment and I was stuck at this place for about couple of days.
Getdate () is not working for this procedure. I used all the suggested methods.
But again I have to use the update statement here. So aren't there any procedure code to make it without using an update statement here?
Update Engineer set Enter_date = getdate() where EmpNo = 'Emp001000'

You don't need #temp_date,change #enter_date to GetDate()
exec sp_Add_New_Engineer #EmpNo='Emp00100', #EngNo= 'E00070' ,
#Eng_Type ='Electrical Engineer', #FName ='Pramila', #LName='Thivagaran',
#DOB ='1994/04/02', #Eng_Address='53/2, Peradeniya Road, Kandy', #Enter_Date = getdate(), #ProNo = 'P6'
Further I recommend formatting your code ,plus don't prefix your sps with SP_ .Here are some issues you may see when you use SP_

Where did you use #Temp_Date. You declared and assigned a value to it but never used in your remaining code. Please refer this sp below. I used your variable instead of #Enter_Date.
ALTER PROCEDURE sp_Add_New_Engineer (
#EmpNo VARCHAR(20)
,#EngNo VARCHAR(12)
,#Eng_Type VARCHAR(50)
,#FName VARCHAR(50)
,#LName VARCHAR(50)
,#DOB VARCHAR(50)
,#Eng_Address VARCHAR(100)
,#Enter_Date DATETIME
,#ProNo VARCHAR(12)
)
AS
DECLARE #Temp_Date DATETIME
SET #Temp_Date = GETDATE()
BEGIN
IF (
(
SELECT count(*)
FROM Supervisor
WHERE EmpNo = #EmpNo
) = 0
)
AND (
(
SELECT count(*)
FROM Labor
WHERE EmpNo = #EmpNo
) = 0
)
BEGIN
INSERT INTO Engineer (
EmpNo
,EngNo
,Eng_Type
,FName
,LName
,DOB
,Eng_Address
,Enter_date
,ProNo
)
VALUES (
#EmpNo
,#EngNo
,#Eng_Type
,#FName
,#LName
,#DOB
,#Eng_Address
,#Temp_Date
,#ProNo
)
END
ELSE
PRINT 'Employee Number is already in use'
END

Related

How to convert a query to a a function

I'm playing around with a query from a software partner that i did not create. I'm trying to use it as a function that i can insert into a table, since i'm no sql expert i'm having difficulties with the sintax.
Thanks to your suggestions i'm making progress, now i'm stuck on how to add an additional select to include some join tables, i have disabled that part converting it to a comment. This actually works without the final select but i need the final select, any ideas?
alter function Renetest
(
#companytest nvarchar(8),
#fiscalyeartest int
)
returns #PERIODBALANCE TABLE
(
[Company] NVARCHAR(8)
,[BookID] NVARCHAR(12)
,[BalanceAcct] NVARCHAR(200)
,[FiscalYear] INT
,[FiscalPeriod] INT
,[BalanceType] NVARCHAR(1)
,[SegValue1] NVARCHAR(50)
,[SegValue2] NVARCHAR(50)
,[FiscalYearSuffix] NVARCHAR(8)
,[FiscalCalendarID] NVARCHAR(12)
)
as
begin
Declare #company nvarchar(8);
Declare #fiscalyear INT;
DECLARE #FiscalPeriod INT;
Set #company = 'epic03'
set #Fiscalyear = '2013'
SET #FiscalPeriod=0;
DECLARE #MaxPeriod AS NVARCHAR(20);
SET #MaxPeriod=(
SELECT
MAX([Erp].[GLBookPer].[FiscalPeriod])
FROM
[Erp].[GLBookPer] WITH (NOLOCK)
WHERE
[Erp].[GLBookPer].[Company] IN (#company)
AND [Erp].[GLBookPer].[FiscalYear]=#FiscalYear
);
WHILE #FiscalPeriod<=(#MaxPeriod)
BEGIN
INSERT INTO #PERIODBALANCE
(
[Company]
,[BookID]
,[BalanceAcct]
,[FiscalYear]
,[FiscalPeriod]
,[BalanceType]
,[SegValue1]
,[SegValue2]
,[FiscalYearSuffix]
,[FiscalCalendarID]
)
SELECT
[Erp].[GLPeriodBal].[Company]
,[Erp].[GLPeriodBal].[BookID]
,[Erp].[GLPeriodBal].[BalanceAcct]
,[Erp].[GLPeriodBal].[FiscalYear]
,#FiscalPeriod AS [FiscalPeriod]
,[Erp].[GLPeriodBal].[BalanceType]
,[Erp].[GLPeriodBal].[SegValue1]
,[Erp].[GLPeriodBal].[SegValue2]
,[Erp].[GLPeriodBal].[FiscalYearSuffix]
,[Erp].[GLPeriodBal].[FiscalCalendarID]
FROM
[Erp].[GLPeriodBal] WITH (NOLOCK)
WHERE
[Erp].[GLPeriodBal].[Company] IN (#company)
AND [Erp].[GLPeriodBal].[FiscalYear]=#FiscalYear
AND [Erp].[GLPeriodBal].[FiscalPeriod]<=#FiscalPeriod
AND [Erp].[GLPeriodBal].[BalanceType] IN ('D','B')
SET #FiscalPeriod=#FiscalPeriod+1;
end;
/*
SELECT
LTRIM(RTRIM([PERIODBALANCE].[Company])) AS [Company]
,LTRIM(RTRIM([PERIODBALANCE].[BookID])) AS [BookID]
,LTRIM(RTRIM(REPLACE([PERIODBALANCE].[BalanceAcct],'|','-'))) AS [BalanceAcct]
,LTRIM(RTRIM(ISNULL(NULLIF([PERIODBALANCE].[BalanceType],''),'--'))) AS [BalanceType]
,LTRIM(RTRIM(ISNULL(NULLIF([PERIODBALANCE].[FiscalYearSuffix],''),'--'))) AS [FiscalYearSuffix]
,LTRIM(RTRIM(ISNULL(NULLIF([PERIODBALANCE].[FiscalCalendarID],''),'--'))) AS [FiscalCalendarID]
FROM
#PERIODBALANCE AS [PERIODBALANCE]*/
return
end
go
The function returns a table. Just select from the function with an INSERT statement.
INSERT INTO dbo.MyTable
SELECT Company, BookID
FROM Renetest();
This is strictly what you asked. But this could be converted into a stored procedure and avoid using a function all together.

Calling a stored procedure in a command object in crystal reports 11 with a date parameter

I have a stored procedure that is in a command object inside a Crystal Report. I need to pass it a date. I defined startdate and enddate in the command parameter window.
This is how I defined the object parameters in Crystal:
Startdate – string . default value = ‘t-1’
Enddate - string. default value = ‘t-1’
It does not error out but runs forever and I have to terminate it. What am I doing wrong?
This is the code inside the command object in Crystal:
DECLARE #StatisticStartDate as datetime = EPIC_UTIL.EFN_DIN({?startdate});
DECLARE #StatisticEndDate as datetime = dateadd(s, 86399, EPIC_UTIL.EFN_DIN({?enddate}));
DECLARE
--#StatisticStartDate nvarchar(20), -- Change all of these to the data types of the specific columns...
--#StatisticEndDate nvarchar(20),
#CostCenterList nvarchar(200),
#ProcedureCodeList nvarchar(100),
#Statistic nvarchar(100),
#StatisticDescription VARCHAR(255),
#RVValue numeric(18,0),
#Fiscalyear int,
#PatientTypeIndicator nvarchar(100),
#PatientServiceList nvarchar(100),
#PatientClassList nvarchar(100),
#PatientStatusList nvarchar(100);
DECLARE #Output TABLE (
[Facility ID] INT,
[Stat Date] DATETIME,
[DEPARTMENT] VARCHAR(200),
[Statistic Name] VARCHAR (200),
[Statistic Description] VARCHAR (200) ,
[Patient Type Indicator] VARCHAR (2),
[Daily Quantity] DECIMAL(18,2) ,
[Daily Amount] DECIMAL(18,2),
COST_CENTER_NAME VARCHAR(200) ,
[Fiscal Year] INT
)
DECLARE Setting_cur CURSOR FOR
SELECT
StatisticStartDate,
StatisticEndDate,
CostCenterList,
ProcedureCodeList,
Statistic,
StatisticDescription,
PatientTypeIndicator,
RVThreshold,
PatientServiceList,
PatientClassList,
PatientStatusList,
FiscalYear
FROM
ssisconfiguration.dbo.BalladHealthDayOneStats
--WHERE
--FiscalYear = 2017
;
OPEN Setting_cur
FETCH NEXT FROM Setting_cur INTO #StatisticStartDate, #StatisticEndDate,
#CostCenterList, #ProcedureCodeList,
#Statistic, #StatisticDescription,
#PatientTypeIndicator, #RVValue,
#PatientServiceList, #PatientClassList,
#PatientStatusList, #FiscalYear
WHILE ##FETCH_STATUS = 0
BEGIN
INSERT #Output
EXEC [SSIS].[sp_BalladDayOneMaster] --#RCout = Clarity.ssis.sp_GetFinancialStatsByFinParams
#SD = #StatisticStartDate,
#ED = #StatisticEndDate,
#CostCenterList = #CostCenterList,
#ProcedureCodeList = #ProcedureCodeList,
#Statname = #Statistic,
#StatDescription = #StatisticDescription,
#PatientTypeIndicator = #PatientTypeIndicator,
#RVvalue = #RVValue,
#FiscalYear = #FiscalYear,
#PatientClassList = #PatientClassList ,
#PatientStatusList = #PatientStatusList,
#PatientServiceList = #PatientServiceList
FETCH NEXT FROM Setting_cur INTO #StatisticStartDate, #StatisticEndDate,
#CostCenterList, #ProcedureCodeList,
#Statistic, #StatisticDescription,
#PatientTypeIndicator, #RVValue,
#PatientServiceList, #PatientClassList,
#PatientStatusList, #FiscalYear
END
CLOSE Setting_cur
DEALLOCATE Setting_cur
SELECT * FROM #Output
Instead of insert all the code inside the command object I would suggest you to create the stored procedure and select that one when you create the new report, so you can debug the stored procedure from sql server.

Stored procedure Date From and Date To

I am trying to create a stored procedure for filtering orders. Basically the users have the option of filtering the order by date from and date to. So they can do search via date from, date to or use both if it makes sense?
Anyhow here is my SQL Server stored procedure so far
ALTER PROCEDURE [dbo].[CN_GetOrderItemByCustID]
#CustomerID int,
#OrderItemWRClass varchar(max) = NULL,
#OrderItemSKUName varchar(50) = NULL,
#OrderItemDateFrom Datetime,
#OrderItemDateTo Datetime
AS
BEGIN
SET NOCOUNT ON;
IF DATEDIFF(d, #OrderItemDateFrom, '01/01/1970') = 0
SET #OrderItemDateFrom = null
IF DATEDIFF(d, #OrderItemDateTo, '01/01/1970') = 0
SET #OrderItemDateTo = null
-- Insert statements for procedure here
SELECT
COM_OrderItem.OrderItemID, COM_Order.OrderID,
COM_Order.OrderDate, COM_OrderItem.OrderItemUnitCount,
COM_OrderItem.OrderItemStatus, COM_OrderItem.OrderItemSKUNAME,
COM_OrderItem.OrderItemSKUID
FROM
COM_OrderItem
INNER JOIN
COM_Order ON COM_Order.OrderID = COM_OrderItem.OrderItemOrderID
WHERE
COM_Order.OrderCustomerID = #CustomerID
OR COM_OrderItem.OrderItemWRClass LIKE #OrderItemWRClass + '%'
OR COM_OrderItem.OrderItemSKUName LIKE #OrderItemSKUName + '%'
OR CONVERT(VARCHAR, COM_Order.OrderDate, 120) LIKE #OrderItemDateFrom + '%'
ORDER BY
COM_Order.OrderDate DESC
However I am not sure on how to put the date from (OrderItemDateFrom) and date to (OrderItemDateTo) in the final SQL statement?
Should I be using OR CONVERT(VARCHAR, COM_Order.OrderDate, 120) LIKE #OrderItemDateFrom + '%' -- which gives me an error
Conversion failed when converting date and/or time from character string.
I know in a normal SQL query I would use Between OrderItemDateFrom and OrderItemDateTo
Thanks
Use this logic
ALTER PROCEDURE [dbo].[CN_GetOrderItemByCustID]
-- Add the parameters for the stored procedure here
#CustomerID int,
#OrderItemWRClass varchar(max) = NULL,
#OrderItemSKUName varchar(50) = NULL,
#OrderItemDateFrom Datetime,
#OrderItemDateTo Datetime
AS
BEGIN
SET NOCOUNT ON;
IF DATEDIFF(d,#OrderItemDateFrom,'01/01/1970')=0 SET #OrderItemDateFrom = '01/01/1970';
IF DATEDIFF(d,#OrderItemDateTo,'01/01/1970')=0 SET #OrderItemDateTo = '31/12/2199';
-- Insert statements for procedure here
SELECT COM_OrderItem.OrderItemID, COM_Order.OrderID, COM_Order.OrderDate, COM_OrderItem.OrderItemUnitCount, COM_OrderItem.OrderItemStatus, COM_OrderItem.OrderItemSKUNAME,
COM_OrderItem.OrderItemSKUID
FROM COM_OrderItem
INNER JOIN COM_Order ON COM_Order.OrderID = COM_OrderItem.OrderItemOrderID
WHERE COM_Order.OrderCustomerID = #CustomerID OR COM_OrderItem.OrderItemWRClass LIKE #OrderItemWRClass + '%' OR COM_OrderItem.OrderItemSKUName LIKE #OrderItemSKUName + '%'
OR (COM_OrderDate>=#OrderItemDateFrom && COM_OrderDate<=#OrderItemDateTo )
ORDER BY COM_Order.OrderDate DESC
Try it . It should work.
Your logic can be simplified a little by allowing NULL values for #OrderItemDateFrom and #OrderItemDateTo. Also, if filters values and column values are all DATETIMEs, you should try to compare directly to allow indexes usages (if any applied on the DATETIME column):
ALTER PROCEDURE [dbo].[CN_GetOrderItemByCustID]
#CustomerID int,
#OrderItemWRClass varchar(max) = NULL,
#OrderItemSKUName varchar(50) = NULL,
#OrderItemDateFrom Datetime = NULL, -- TODO: change caller to not provide parameter, or leave it to null
#OrderItemDateTo Datetime = NULL -- TODO: change caller to not provide parameter, or leave it to null
AS
BEGIN
SET NOCOUNT ON;
-- when working with dates try to use an unambiguous format like 'YYYY-MM-DD'
SET #OrderItemDateFrom = ISNULL(#OrderItemDateFrom, '1970-01-01')
-- assign a very large date to act like not provided
-- going one day after to catch DATETIMEs with provided time
SET #OrderItemDateTo = DATEADD(day, 1, ISNULL(#OrderItemDateTo, '3000-01-01'))
-- Insert statements for procedure here
SELECT
COM_OrderItem.OrderItemID, COM_Order.OrderID,
COM_Order.OrderDate, COM_OrderItem.OrderItemUnitCount,
COM_OrderItem.OrderItemStatus, COM_OrderItem.OrderItemSKUNAME,
COM_OrderItem.OrderItemSKUID
FROM COM_OrderItem
INNER JOIN COM_Order ON COM_Order.OrderID = COM_OrderItem.OrderItemOrderID
WHERE COM_Order.OrderCustomerID = #CustomerID
OR COM_OrderItem.OrderItemWRClass LIKE #OrderItemWRClass + '%'
OR COM_OrderItem.OrderItemSKUName LIKE #OrderItemSKUName + '%'
-- between can be used
OR (COM_OrderDate BETWEEN #OrderItemDateFrom AND #OrderItemDateTo)
ORDER BY
COM_Order.OrderDate DESC
END
Another option is to use dynamic SQL and construct it based on parameters values (i.e. insert WHERE condition if filter value is provided). This is particularly useful when filters numbers is relatively low compared to the total number of filters, as ORs are not performance friendly.
NOTE: shouldn't your filters apply in conjuction (i.e. use AND instead of OR)? It would make sense to allow the user to filter by several value in the same time.
ALTER PROCEDURE [dbo].[CN_GetOrderItemByCustID]
#CustomerID int,
#OrderItemWRClass varchar(max) = NULL,
#OrderItemSKUName varchar(50) = NULL,
#OrderItemDateFrom Datetime,
#OrderItemDateTo Datetime
AS
BEGIN
SET NOCOUNT ON;
IF DATEDIFF(d, #OrderItemDateFrom, '01/01/1970') = 0
SET #OrderItemDateFrom = null
IF DATEDIFF(d, #OrderItemDateTo, '01/01/1970') = 0
SET #OrderItemDateTo = null
-- Insert statements for procedure here
SELECT
COM_OrderItem.OrderItemID, COM_Order.OrderID,
COM_Order.OrderDate, COM_OrderItem.OrderItemUnitCount,
COM_OrderItem.OrderItemStatus, COM_OrderItem.OrderItemSKUNAME,
COM_OrderItem.OrderItemSKUID
FROM
COM_OrderItem
INNER JOIN
COM_Order ON COM_Order.OrderID = COM_OrderItem.OrderItemOrderID
WHERE
COM_Order.OrderCustomerID = #CustomerID
OR COM_OrderItem.OrderItemWRClass LIKE #OrderItemWRClass + '%'
OR COM_OrderItem.OrderItemSKUName LIKE #OrderItemSKUName + '%'
OR (#OrderItemDateFrom IS NULL OR COM_Order.OrderDate >=#OrderItemDateFrom)
OR (#OrderItemDateTo IS NULL OR COM_Order.OrderDate <=#OrderItemDateTo)
ORDER BY
COM_Order.OrderDate DESC
You should Try this.
OR (#OrderItemDateFrom IS NULL OR COM_Order.OrderDate >=#OrderItemDateFrom)
OR (#OrderItemDateTo IS NULL OR COM_Order.OrderDate <=#OrderItemDateTo)
Just Edit and try this condition..

SQL: Procedure not getting a date null

I’m executing a procedure like this:
EXEC myProcedure #name = 'Smith', #dateDeleted = NULL
I need all the Smith that don’t have a deleted date.
And this is the procedure:
CREATE PROCEDURE [dbo].[myProcedure]
#name VARCHAR(8000) = NULL
,#dateDeleted VARCHAR(8000) = NULL
AS
BEGIN
SET NOCOUNT ON;
WITH t
(name
,dateDeleted
)
AS
(
SELECT DISTINCT
name,dateDeleted FROM mytable
WHERE
(#name IS NULL OR #name = name)
AND (#dateDeleted IS NULL OR CONVERT(DATETIME, #dateDeleted, 102) = dateDeleted)
)
After the execution I have all the Smith but it does not pay any attention to the dateDeleted = NULL .. I ge all the Smiths no matter if they have a deleted date
How can I fix this?
Thanks
In your request if you pass NULL then a condition always true.Try this WHERE clause with COALESCE expression:
WHERE (#name IS NULL OR #name = name)
AND (COALESCE(#dateDeleted, dateDeleted) IS NULL
OR CONVERT(DATETIME, #dateDeleted, 102) = dateDeleted)
You need to set ansi nulls on
Execute:
set ansi_nulls on
And then execute the query.
Here is the explantion for this behaviour
http://msdn.microsoft.com/en-us/library/ms188048.aspx

Can't insert a second row into a table though it insert first row by stored procedure

It inserted a first row successfully but it's not inserting any other row, though second row has no conflict of primary key
Code in my aspx.cs file:
outputParVal = sqlCmd.Parameters[outputParName].Value;
outparameter in stored procedure is--- "Result"
CREATE PROCEDURE [dbo].[RecruiterProfileInsert]
#CompanyId int,
#CompanyName varchar(200),
#EmailId varchar(50) ,
#Password varchar(20) ,
#ContactNumber varchar(15),
#Website varchar(50),
#CompanyProfile varchar(2000),
#IsVerified bit,
#Result Tinyint OutPut
--#CreatedDate datetime ,
--UpdatedDate datetime
AS
BEGIN
-- Insert statements for procedure here
--check whether #CompanyName already exist or not if exist then return
IF EXISTS(SELECT Top 1 * FROM RecruiterProfile WHERE #CompanyId = LTRIM(RTRIM(#CompanyId)))
BEGIN
SET #Result = 0-- Already Exists
END
ELSE
BEGIN
INSERT INTO RecruiterProfile
(
CompanyId,
CompanyName,
EmailId ,
Password ,
ContactNumber,
Website ,
CompanyProfile ,
IsVerified,
CreatedDate
)
VALUES
(
#CompanyId,
#CompanyName,
#EmailId ,
#Password,
#ContactNumber,
#Website,
#CompanyProfile,
#IsVerified,
GetDate()
)
set #Result =1
return
END
END
This is the problem:
SELECT Top 1 * FROM RecruiterProfile WHERE #CompanyId = LTRIM(RTRIM(#CompanyId))
This inherently makes no sense. You're comparing the variable to itself. Take the # sign out of one of the CompanyId references. The RTrim is unnecessary in SQL Server, and the LTrim doesn't make sense either because the later insert doesn't also LTrim so something is going to go wrong eventually.
Furthermore, inside of an EXISTS clause, TOP makes no sense unless you are using ORDER BY and doing something with the final result. Just do SELECT * inside of EXISTS clauses.
One more thing: if there is high concurrency and users could possibly try to insert the same thing at the same time, your query could still fail on a duplicate key violation.

Resources