Count all files in a directory using datetime - sql

I'm almost there with a script to count the files in the last 18 hours in a specific directory. We expect 12 a day, so it's good for the person running the script to see how many files are there, and can investigate based on this script.
My current script is as follow:
DECLARE #Now DATETIME= GetDate() --Get now
DECLARE #TimeD INT = -18 --Number of hours to look into the past
create table #regop(
[date] dateTime,
depth int,
[file] int)
insert into #regop
EXECUTE master.dbo.xp_dirtree N'\\location...\', 1, 1
select count([file]) from #regop
WHERE TRY_CONVERT(date, LEFT([date],8), 1) = CONVERT(date, GETDATE())
and [file]=1 and [date] >= DATEADD(HH,#TimeD,#Now)
drop table #regop
I'm currently getting
Msg 8114, Level 16, State 1, Procedure xp_dirtree, Line 1 [Batch Start Line 0]
Error converting data type nvarchar to datetime.
Can anyone assist where I'm going wrong?

To be honest I think it is not possible to retrieve data when the file was created with xp_dirtree. As an first output argument that function returns file name which is nvarchar, not an data. That part cause an error. You can fix that by changing data type in temporary table:
create table #regop(
--[date] dateTime,
[file_name] nvarchar(512),
depth int,
[file] int)

Related

SQL Server 'Operand type clash: int is incompatible with date' error

I wanted to create a membership limit to the database. For this, I added using the ALTER command. Then I wanted to return the number of months remaining until the end of membership with a function, but I got the error
Operand type clash: int is incompatible with date.
I am getting the error while trying to create the function. This is exactly how it is:
Msg 206, Level 16, State 2, Procedure getMembershipExpiration, Line 1
Operand type clash: int is incompatible with date
ALTER TABLE Member
ADD Membership_End_Date DATE DEFAULT '2099-01-01' not null
CREATE FUNCTION getMembershipExpiration(#Member_ID int)
RETURNS date
AS
BEGIN
DECLARE #endDate date = (SELECT Membership_End_Date FROM Member WHERE Member_ID =#Member_ID)
DECLARE #nnow date = (SELECT GETDATE())
DECLARE #remainingMonth date = (SELECT DATEDIFF(MONTH,#nnow ,#endDate ))
RETURN #remainingMonth
END
As a solution, it was suggested to put the date part in quotation marks and write it in the YYYY-MM-DD pattern, but it did not lead me to the solution.
DATEDIFF returns int, not date. Replace line #5 with:
RETURNS int
and line #12 with:
DECLARE #remainingMonth int = (SELECT DATEDIFF(MONTH,#nnow ,#endDate ))

How to insert a cast conversion into database

I've been trying to insert a varchar value into a table in SQL using a cast.
The varchar input values has a string datetime format like this:
'08/25/2022 03:34:59 PM'
The fechaInicio column is originally filled with NULL, and the purpose of the stored procedure is to update that column with the #strDateTime value sent.
Example of my table [Table_Input]:
fechaInicio
ID
NULL
2
If I just do a
SELECT CAST('08/25/2022 03:34:59 PM' AS DATETIME)
it actually works and shows me the correct casting in the message window. But the problem is when I try to update into the table.
I removed my try-except commands to see the error.
If I call the stored procedure like this
[SP_Table_Input_Get_Series] '08/25/2022 03:34:59 PM', 2
I get the following error:
Msg 241, Level 16, State 1, Procedure SP_Table_Input_Get_Series, Line 34 [Batch Start Line 13]
Conversion failed when converting date and/or time from character string
My stored procedure is something like this:
PROCEDURE [SP_Table_Input_Get_Series]
#strDateTime NVARCHAR(50),
#cId int
AS
BEGIN TRANSACTION
UPDATE [Table_Input]
SET
---fechaInicio =convert(datetime, #strDateTime, 5),
---fechaInicio = N'select cast(#strDateTime as datetime)'
fechaInicio = CAST(#strDateTime AS datetime)
WHERE id = #cId -- the where clause works fine
COMMIT TRANSACTION
All the 3 options (including commented ones in the stored procedure) didn't work.
Also a constraint is I cannot modify the column type to varchar or any other type.
I will really appreciated if someone can help me find a solution.
I'm running the stored procedure directly in Microsoft SQL Server Management Studio.
Please try the following solution.
As #AlwaysLearning pointed out, I changed 89 to 59 seconds.
SQL
-- DDL and sample data population, start
DECLARE #tbl TABLE (ID INT IDENTITY PRIMARY KEY, fechaInicio DATETIME2(0));
INSERT #tbl (fechaInicio) VALUES
(GETDATE());
-- DDL and sample data population, end
DECLARE #strDateTime VARCHAR(50) = '08/25/2022 03:34:59 PM';
-- before
SELECT * FROM #tbl;
UPDATE #tbl
SET fechaInicio = convert(DATETIME2(0), #strDateTime, 101)
where ID = 1;
-- after
SELECT * FROM #tbl;
Output
ID
fechaInicio
1
2022-08-25 15:34:59

Need assistance with the format of a SQL Server table-valued function

I have never used a TVF before and I need to use it to run a query in PowerBI DirectQuery.
I'm re-utilizing the query I already have in use in a stored procedure, where I declare and use a couple of variables to capture a date range.
I get the following error:
Msg 156, Level 15, State 1, Procedure usf_PBI_AgentProd, Line 21 [Batch Start Line 8]
Incorrect syntax near the keyword 'SET'
My code is as follows:
CREATE FUNCTION [dbo].[usf_PBI_AgentProd]()
RETURNS TABLE
AS
RETURN
SET DATEFIRST 7
DECLARE #Oggi date = GETDATE()
DECLARE #Start datetime = CAST(#Oggi AS datetime) + CAST('00:00' AS datetime)
DECLARE #End datetime = CAST(#Oggi AS datetime) + CAST('23:59' AS datetime);
SELECT
t.AgentName, t.AgtID,
n.SalesArea, t.TotRes, t.ResDate
FROM
rxtdoc t
INNER JOIN
rstdhdr n ON (1 = 1)
WHERE
ResDate BETWEEN #Start AND #End
I know this might be entry level sql code for most of you, but at this moment I'm stuck, so I'd appreciate if any of you could lend a hand.
Thank you!!
Slight syntax error causing the issue.
You can only use
CREATE FUNCTION dbo.myFunct(x int)
RETURNS TABLE
AS
RETURN
if all you have in your function is a SELECT statement. You, however, have quite a few things before your SELECT statement that make this an issue.
If you have other things you want to do before you return data, use this syntax instead:
CREATE FUNCTION [dbo].[usf_PBI_AgentProd2]()
/** Note how you have to explicitly lay out your table definition **/
RETURNS #myReturnTable TABLE (
agentName varchar(50),
agtID int,
salesArea varchar(150),
totRes int,
resDate datetime
)
AS
BEGIN;
/* This seems really unnecessary, but you know your code best */
SET DATEFIRST 7;
DECLARE #Oggi date = getdate () ;
DECLARE #Start datetime = CAST(#Oggi AS datetime) + CAST('00:00' AS datetime);
DECLARE #End datetime = CAST(#Oggi AS datetime) + CAST('23:59' AS datetime);
/* you can honestly do almost anything in this area */
-- When you're ready to populate that return table, do so like this
INSERT INTO #myReturnTable
Select
t.AgentName
,t.AgtID
,n.SalesArea
,t.TotRes
,t.ResDate
from
rxtdoc t
INNER JOIN rstdhdr n ON(1=1)
where
ResDate between #Start and #End
RETURN;
END;
Some useful help: https://www.sqlservertutorial.net/sql-server-user-defined-functions/sql-server-table-valued-functions/

Getting error when inserting into temptable

I have a #temptable which I'm trying to populate but its not working.
DECLARE
#nBranchId int
,#tmStartDate datetime
,#tmEndDate datetime
SELECT #nBranchId = 3483
,#tmStartDate = DATEADD(DAY, -10, GETDATE())
,#tmEndDate = GETDATE()
CREATE table #temptable (
nResultsId int
,nInstrId int
,nBranchId int
,nFoldersId int
,strPaperId varchar(50)
,strPosName varchar(50)
,fQuantity float
,fRevaluationPrice float
,fHistRevaluationPrice float
,tmDate datetime
,nPrevResultsId int
)
INSERT INTO #temptable
SELECT
xpr.nResultsId
,xpr.nInstrId
,xpr.nBranchId
,xpr.nFoldersId
,xpr.strPaperId
,xpr.strPosName
,xpr.fQuantity
,xpr.fRevaluationPrice
,xpr.fHistRevaluationPrice
,xpr.tmDate
,nPrevResultsId = dbo.fnGetPrevTradeResultId(xpr.nBranchId, xpr.nInstrId, xpr.strPaperId, xpr.strPosName,xpr.tmDate, xpr.nFoldersId)
FROM dbo.XP_Results AS xpr WITH(READUNCOMMITTED)
WHERE 1 = 1
AND xpr.nBranchId = ISNULL(#nBranchId, xpr.nBranchId)
AND xpr.tmDate BETWEEN #tmStartDate AND #tmEndDate
AND xpr.nInstrId <> 18
DROP table #temptable
Getting this error:
Msg 8152, Level 16, State 14, Line 28
String or binary data would be truncated.
The statement has been terminated.
Where am I missing it? Have looked and looked but can't solve it
You have different length data types
To avoid this problem use a SELECT INTO statement
#Temptable would be created automatically with correct data type (Extra benefit you don't have to script CREATE statement)
DECLARE
#nBranchId int
,#tmStartDate datetime
,#tmEndDate datetime
SELECT #nBranchId = 3483
,#tmStartDate = DATEADD(DAY, -10, GETDATE())
,#tmEndDate = GETDATE()
SELECT xpr.nResultsId
,xpr.nInstrId
,xpr.nBranchId
,xpr.nFoldersId
,xpr.strPaperId
,xpr.strPosName
,xpr.fQuantity
,xpr.fRevaluationPrice
,xpr.fHistRevaluationPrice
,xpr.tmDate
,nPrevResultsId = dbo.fnGetPrevTradeResultId(xpr.nBranchId, xpr.nInstrId, xpr.strPaperId, xpr.strPosName,xpr.tmDate, xpr.nFoldersId)
INTO #temptable
FROM dbo.XP_Results AS xpr WITH(READUNCOMMITTED)
WHERE 1 = 1
AND xpr.nBranchId = ISNULL(#nBranchId, xpr.nBranchId)
AND xpr.tmDate BETWEEN #tmStartDate AND #tmEndDate
AND xpr.nInstrId <> 18
DROP table #temptable
Should be fixed by changing these two columns to look like this. Likely what is going on is, you are trying to insert varchars greater than 50 characters into a varchar(50) column.
strPaperId varchar(max),
strPosName varchar(max)
That means that one of your columns has data that is larger than the data type size you declared for the temp table column.
For example, if you have a temp table column of varchar(2), then try to insert the value '123', you would get that error message because the value we are inserting is longer than the size of the column you are inserting into. Note that this message can mean any type.
Find the temp table column with the problem and increase the size to the size in the actual table.

Convert Parameter Value Form DateTime To Int32

I am having problems with a Stored Procedure I am writing.
I am gathering data from a number of tables, most of which hold a date value, but one holds just a month(int)
I declare the following Parameters at the beginning of my SP.
#FromDate DateTime,
#ToDate DateTime
This works fine for most of my tables, but for the table where I am just requiring the Month from the #FromDate, I run into the following error:
"Failed to convert parameter value form a DateTime to a Int32."
Here is my Select statement for the Problem Table:
SELECT Branch, Discount
FROM MonthlyPromotions
WHERE (Month = DATEPART(mm,#FromDate))
Also, in the MonthlyPromotions Table the Month Field is an Int.
Can anyone help on this ASAP??
Thankyou
To troubleshoot your problem, can you do a
PRINT CAST(CAST(DATEPART(mm, #FromDate) AS INT) AS VARCHAR(50))
RETURN
At the beginning of your SP?
If that doesn't give an error, you can proceed to:
SELECT Branch, Discount
FROM MonthlyPromotions
WHERE Month = CAST(DATEPART(mm,#FromDate) AS INT)
select cast(getdate() as int)