Error in SQL. Can not find it.
DECLARE #year VARCHAR (4),
#month VARCHAR (2),
#day VARCHAR (2),
#weekday VARCHAR (2),
#hour VARCHAR (2),
#archivePath VARCHAR (128),
#archiveName VARCHAR (128),
#archiveFullName VARCHAR (128)
SET #year = CAST(DATEPART(yyyy, GETDATE()) AS VARCHAR)
SET #month = CAST(DATEPART(mm, GETDATE()) AS VARCHAR)
SET #day = CAST(DATEPART(dd, GETDATE()) AS VARCHAR)
SET #weekday = CAST(DATEPART (dw, GETDATE()) AS VARCHAR)
SET #hour = CAST(DATEPART (hh, GETDATE()) AS VARCHAR)
SET #archivePath = 'd:\1c_new\backupdb\'
SET #archiveName = 'TransactionLog_' + #year + '_' + #month + '_' + #day + '_' + #hour + '.bak'
SET #archiveFullName = #archivePath + #archiveName
BACKUP LOG [xxx] TO DISK = #archiveFullName WITH INIT , NOUNLOAD , NAME = N'Ежечастный лог транкзаций', SKIP , STATS = 10, DESCRIPTION = N'Ежечастный лог транкзаций', NOFORMAT
Just a hunch, try changing N'Ежечастный лог транкзаций' to something like 'NORMAL STRING'
Related
I want to create a datetime with a value like:
2019-09-01 00:00:00.000
I have the values for year and month in variables #year and #month.
What is the best way to create a datetime with inputs?
I would use DATEFROMPARTS.
declare #year int = 2019
, #month int = 9
SELECT convert(datetime, DATEFROMPARTS(#year, #month, 1))
I'm include a #Day part too, as you may find it useful. If you do not want it, replace RIGHT('00' + LTRIM(#Day),2) with '01'
DECLARE #Year VARCHAR(4) = '2019';
DECLARE #Month VARCHAR(2) = '09'
DECLARE #Day VARCHAR(2) = '01'
SELECT CAST(CAST(#Year as char(4))
+ RIGHT('00' + LTRIM(#Month),2)
+ RIGHT('00' + LTRIM(#Day),2)
AS Datetime)
I want to create a dynamic table in SQL Server using dynamic Table name and dynamic Column name. For example:
Table name : 01-02-2015
Column names:
Id 01 02 03.... 28
When I creating a temp table is OK but I want to create a real Table then I use the following script like this, when execute the error occur:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '.01'.
Code:
DECLARE #DynamicSQL as NVARCHAR(max),#TempTableName as nvarchar(max)
DECLARE #TimeSheetDate as DateTime
DECLARE #startDate AS DATETIME --Cursor Local Variables
DECLARE #endDate AS DATETIME
SET #TimeSheetDate = '2015-2-15'
SET #startDate = DATEADD(mm, DATEDIFF(mm, 0, #TimeSheetDate), 0) -- the first day of month
SET #endDate = DATEADD (dd, -1, DATEADD(mm, DATEDIFF(mm, 0, #TimeSheetDate) + 1, 0))-- the last day of month
SET #TempTableName = #startDate -- the first day of month
SET #DynamicSQL='CREATE TABLE dbo.'+ quotename(#TempTableName, '[') + '(Id int identity(1,1) not null primary key);';
WHILE (#startDate <= #endDate)
BEGIN
--DECLARE #DynamicSQL VARCHAR(500)
BEGIN
SET #DynamicSQL = 'ALTER TABLE dbo.' + #TempTableName +
' ADD ['+ CONVERT(VARCHAR(2), #startDate, 105) + '] NVARCHAR(max) NULL'
EXECUTE (#DynamicSQL)
END
SET #startDate = DateADD(dd, 1, #startDate)
IF #startDate - 1 = #endDate
BREAK;
END
exec (#DynamicSQL);
If I use this script to create a temp table is OK:
DECLARE #TempTableName as nvarchar(100)
DECLARE #TimeSheetDate as DateTime
DECLARE #startDate AS DATETIME --Cursor Local Variables
DECLARE #endDate AS DATETIME
SET #TimeSheetDate = '2015-2-15'
SET #startDate = DATEADD(mm, DATEDIFF(mm, 0, #TimeSheetDate), 0)
SET #endDate = DATEADD (dd, -1, DATEADD(mm, DATEDIFF(mm, 0, #TimeSheetDate) + 1, 0))
SET #TempTableName = DATEADD(mm, DATEDIFF(mm, 0, #TimeSheetDate), 0)
if exists (select * from tempdb.dbo.sysobjects o where o.xtype in ('U') and o.id = object_id(N'tempdb..##TempTableName'))
DROP TABLE ##TempTableName
CREATE TABLE ##TempTableName(Id int identity(1,1) not null primary key) -- Creating Temp Table
-- Loop to add columns to temp table
WHILE (#startDate <=#endDate)
BEGIN
DECLARE #DynamicSQL VARCHAR(500)
BEGIN
SET #DynamicSQL = 'ALTER TABLE ##TempTableName ADD ['+ CONVERT(VARCHAR(2),#startDate,105) +'] NVARCHAR(100) NULL'
EXECUTE (#DynamicSQL)
END
SET #startDate = DateADD(dd,1,#startDate)
IF #startDate-1 = #endDate
BREAK;
END
SELECT * FROM ##TempTableName
The problem is in your alter table statement.
Change
SET #DynamicSQL = 'ALTER TABLE dbo.' + #TempTableName +
' ADD ['+ CONVERT(VARCHAR(2), #startDate, 105) + '] NVARCHAR(max) NULL'
To
SET #DynamicSQL = 'ALTER TABLE dbo.' + quotename(#TempTableName, '[') +
' ADD ['+ CONVERT(VARCHAR(2), #startDate, 105) + '] NVARCHAR(max) NULL'
This works for my expectation:
ALTER PROCEDURE [dbo].[proc_InsertTimeSheetInit]
#TimeSheetDate as DateTime
AS
BEGIN
DECLARE #DynamicSQL as NVARCHAR(255)
DECLARE #TableName as nvarchar(255)
DECLARE #startDate AS DATETIME
DECLARE #endDate AS DATETIME
DECLARE #dropSQL as NVARCHAR(255)
SET #startDate = DATEADD(mm, DATEDIFF(mm, 0, #TimeSheetDate), 0) -- the first day of month
SET #endDate = DATEADD (dd, -1, DATEADD(mm, DATEDIFF(mm, 0, #TimeSheetDate) + 1, 0))-- the last day of month
SET #TableName ='TS'+convert(nvarchar(2), datepart(mm, #TimeSheetDate)) + convert(nvarchar(4), datepart(yyyy, #TimeSheetDate))
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].['+ #TableName+ ']') AND type in (N'U'))
SELECT #dropSQL = 'DROP TABLE dbo.' + QUOTENAME(#TableName) + '';
exec (#dropSQL)
SET #DynamicSQL = 'create table [dbo].[' + #TableName + ']([Id] [int] IDENTITY(1,1) NOT NULL,CONSTRAINT PK_'+#TableName+' PRIMARY KEY CLUSTERED (Id))'
exec (#DynamicSQL)
WHILE (#startDate <= #endDate)
BEGIN
BEGIN
SET #DynamicSQL = 'ALTER TABLE [dbo].[' + #TableName + '] ADD ['+ CONVERT(VARCHAR(2), #startDate, 105) + '] NVARCHAR(50) NULL'
EXECUTE (#DynamicSQL)
END
SET #startDate = DateADD(dd, 1, #startDate)
IF #startDate - 1 = #endDate
BREAK;
END
END
I have stored procedure like this on my DB:
ALTER procedure [dbo].[performance]
(#startdate nvarchar(100), #enddate nvarchar(100)
as begin
declare #date1 nvarchar(100) = convert(varchar, #startdate+' 00:00:00.000', 120)
declare #date2 nvarchar(100) = convert(varchar, #enddate+' 23:59:59.000', 120)
set NOCOUNT on;
select l.LocName,v.Vtype, SUM(DATEDIFF(MI,t.Paydate,t.DelDate)) as TotalDiff,
[dbo].[testfunction](
CONVERT(decimal(10,1), AVG( CONVERT(NUMERIC(18,2), DATEDIFF(SS,t.Paydate,t.DelDate) ) ))) as Average
from Transaction_tbl t
left join VType_tbl v
on t.vtid=v.vtid
left join Location_tbl l
on t.Locid=l.Locid
where t.Locid in
(select t1.Locid from Transaction_tbl t1)
and dtime between '' + #date1 +'' and ''+ #date2 +''
and Status =5
group by v.Vtype,l.LocName,l.Locid order by l.Locid
end
my testfunction ike this:
ALTER FUNCTION [dbo].[testfunction] (#dec NUMERIC(18, 2)) RETURNS Varchar(50)
AS
BEGIN
DECLARE
#hour integer,
#Mns integer,
#second decimal(18,3)
DECLARE #Average Varchar(50)
select #hour=CONVERT(int,#dec/60/60)
SELECT #Mns = convert(int, (#dec / 60) - (#hour * 60 ));
select #second=#dec % 60;
SELECT #Average =
convert(varchar(9), convert(int, #hour)) + ':' +
right('00' + convert(varchar(2), convert(int, #Mns)), 2) + ':' +
right('00' + CONVERT(decimal(10,0), convert(varchar(6), #second)), 6)
RETURN #Average
END
if i pass start date:2013-06-01 and end date:2013-08-01 then getting proper out put
if i pass start date:2010-06-01 and end date:2013-08-01 (bigger date difference) then getting error:
Arithmetic overflow error converting numeric to data type varchar.
i know having some problem with my function.but i am not able find out what is the issue with my function.if any one please help me to find out
try this .. i think your #Mns should be the problem
ALTER FUNCTION [dbo].[testfunction] (#dec NUMERIC(18, 2)) RETURNS Varchar(50)
AS
BEGIN
DECLARE
#hour decimal(18,2),
#Mns decimal(18,2),
#second decimal(18,3)
DECLARE #Average Varchar(50)
select #hour=CONVERT(int,#dec/60/60)
SELECT #Mns = convert(int, (#dec / 60) - (#hour * 60 ));
select #second=#dec % 60;
SELECT #Average =
convert(varchar(9), convert(int, #hour)) + ':' +
right('00' + convert(varchar(8), convert(decimal(18,2), #Mns)), 2) + ':' +
right('00' + CONVERT(decimal(10,0), convert(varchar(10), #second)), 6)
RETURN #Average
END
I am receiving a date and a time field from an access database and they are separate varchar fields. I am importing the data into an sql database. I want to display the data as a date time field but I can't get the data to format in the normal manner. I have come up with a substring to format the data but I am having problems getting it either into a cursor or a loop to get all of the data to update. I want to format my import table first before I move it to another table in sql. Here is code that I have for the date and time to format it. Any help would be appreciated.
Time
declare #result varchar(10), #time varchar(6), #hour varchar(2), #min varchar(2), #sec varchar (2);
Select #time = time_of_call from import
Set #hour = substring(#time, 1, 2);
Set #min = substring(#time, 3, 2);
Set #sec = substring(#time, 5, 2);
If #hour < '12'
Set #result = #hour + ':' + #min + ' AM';
else if #hour >= '12'
Set #result = #hour + ':' + #min + ' PM';
Select #result;
Date
declare #result varchar(12), #date varchar(8), #year varchar(4), #month varchar(2), #day varchar(2);
Select #date = date_of_call from import
Set #year = substring(#date, 1, 4);
Set #month = substring(#date, 5, 2);
Set #day = substring(#date, 7, 2);
Set #result = #month + '/' + #day + '/' + #year;
Select #result
--- some sample data
create table import (time_of_call varchar(6), date_of_call varchar(8));
insert into import values ('101112', '20121110');
insert into import values ('134526', '20130201');
--- the query
select cast(date_of_call + ' ' +
substring(time_of_call, 1, 2) + ':' +
substring(time_of_call, 3, 2) + ':' +
substring(time_of_call, 5, 2) as datetime) AsDateTime,
cast(date_of_call + ' ' +
substring(time_of_call, 1, 2) + ':' +
substring(time_of_call, 3, 2) + ':' +
substring(time_of_call, 5, 2) as datetime) AsString
from import;
----------------------- -----------------------
AsDateTime AsString
----------------------- -----------------------
2012-11-10 10:11:12.000 2012-11-10 10:11:12.000
2013-02-01 13:45:26.000 2013-02-01 13:45:26.000
I have a procedure to fetch data as per the criteria passed. I works fine with #month, #year, #quater.
ALTER PROCEDURE dbo.SPReportTimeSpan
(
#Week int = null,
#Month int = null,
#Year int = null,
#Quater int = null
)
AS
SET NOCOUNT ON
DECLARE #sql nvarchar(4000)
If (#Week) IS NOT NULL
BEGIN
DECLARE #startdate Date, #enddate Date
EXEC dbo.SPReturnStartEndDateOfSpecifiedWeek #Week, #startdate OUTPUT, #enddate OUTPUT
SELECT #startdate, #enddate
END
SELECT #sql='SELECT
CRMDR.Id as Id,.
CRMDR.Request_For_Id as Request_For_Id
From [CRM].[dbo].[CRM_Doctor_Request] AS CRMDR
WHERE CRMDR.Is_Deleted=0 '
If (#Month) IS NOT NULL
SELECT #sql=#sql + ' AND MONTH(CRMDR.Date_Created) like (#Month) '
If (#Year) IS NOT NULL
SELECT #sql=#sql + ' AND YEAR(CRMDR.Date_Created) like (#Year) '
If (#Week) IS NOT NULL
SELECT #sql=#sql + ' AND (CRMDR.Date_Created) BETWEEN (#startdate) AND (#enddate) '
If (#Quater) IS NOT NULL
IF (#Quater = 1)
SELECT #sql=#sql + ' AND MONTH(CRMDR.Date_Created) in (4,5,6) '
IF (#Quater = 2)
SELECT #sql=#sql + ' AND MONTH(CRMDR.Date_Created) in (7,8,9) '
IF (#Quater = 3)
SELECT #sql=#sql + ' AND MONTH(CRMDR.Date_Created) in (10,11,12) '
IF (#Quater = 4)
SELECT #sql=#sql + ' AND MONTH(CRMDR.Date_Created) in (1,2,3) '
SELECT #sql=#sql + ' ORDER BY CRMDR.Id DESC '
EXEC sp_executesql #sql, N'#Month int, #Year int, #Quater int',
#Month, #Year, #Quater
RETURN
But for #week it gives error.
Running [dbo].[SPReportTimeSpan] ( #Week = 3, #Month = <NULL>, #Year = <NULL>, #Quater = <NULL> ).
Must declare the scalar variable "#startdate".
Column1 Column2
------------------------------ ------------------------------
2013-02-10 00:00:00.0000000 2013-02-17 00:00:00.0000000
No rows affected.
(1 row(s) returned)
#RETURN_VALUE = 0
Finished running [dbo].[SPReportTimeSpan].
I am not getting why its not working with week criteria. Please help if anyone have idea.
#startdate and #enddate are only accessible within the scope of your IF statement:
If (#Week) IS NOT NULL
BEGIN
DECLARE #startdate Date, #enddate Date
EXEC dbo.SPReturnStartEndDateOfSpecifiedWeek #Week, #startdate OUTPUT, #enddate OUTPUT
SELECT #startdate, #enddate
END
Move the declaration outside of the IF statement if you wish to reference these variables elsewhere:
DECLARE #startdate Date, #enddate Date
If (#Week) IS NOT NULL
BEGIN
EXEC dbo.SPReturnStartEndDateOfSpecifiedWeek #Week, #startdate OUTPUT, #enddate OUTPUT
SELECT #startdate, #enddate
END
FYI: The area where you make reference to these variables outside of the IF statement is here:
If (#Week) IS NOT NULL
SELECT #sql=#sql + ' AND (CRMDR.Date_Created) BETWEEN (#startdate) AND (#enddate) '
I got solution of my problem. To solve the problem, I need to explicitly cast datetime values to a character type so the query string can be concatenated as expected.
If (#Week) IS NOT NULL
SELECT #sql=#sql + ' AND (CRMDR.Date_Created) BETWEEN ''' + convert(VARCHAR,#startdate) + ''' AND ''' +convert(VARCHAR,#enddate) + ''''
or this (More Optimized)
SELECT #sql=#sql + ' AND (CRMDR.Date_Created BETWEEN #startdate AND #enddate)'
which needs to add something to sp_executesql
EXEC sp_executesql #sql, N'#Month int, #Year int, #Quater int, #Week int, #startdate datetime, #enddate datetime ',
#Month, #Year, #Quater, #Week, #startdate, #enddate
Your variables are out of scope.