This question already has an answer here:
operation not allowed when the object is closed when running more advanced query
(1 answer)
Closed 6 years ago.
I am trying to query a SQL Server 2008 instance from VBScript.
I know my connection is working because when I use a simple query such as the one below it works fine.
sfQuery2 = "SELECT TOP 10 * FROM [DB].[schema].[table]"
The one thing I am unsure about is the user that I am connected as has read only rights. Not sure if the userid will be able to create temp tables if they are read only. I did run the same query from SQL Server with this user and the query worked. But when I try to run this with the same user from vbscript when I try to read the record set the error I get is.....
ADODB.Recordset: Operation is not allowed when the object is closed.
sfQuery2 = "CREATE TABLE #Temp1 ([LOGNAME] [nvarchar](20) NULL, [MESSAGE_TYPE] [int] NULL, [COMPONENT] [nvarchar](50) NULL, [LOGTIME] [nvarchar](17) NOT NULL, [SUB_SYSTEM] [nvarchar](40) NULL, [STACK_ID] [nvarchar](120) NULL, [SUBSTACK_ID] [int] NULL, [MESSAGE] [nvarchar](1800) NULL, [DETAIL] [nvarchar](1800) NULL ) INSERT INTO #Temp1 SELECT DISTINCT [LOGNAME], [MESSAGE_TYPE], [COMPONENT], LOGTIME, [SUB_SYSTEM], [STACK_ID], [SUBSTACK_ID], [MESSAGE], [DETAIL] FROM [DB].[schema].[table] WHERE cast(LEFT(LOGTIME,8) as date) = cast(getdate() -1 as date) AND [MESSAGE] LIKE '%Exporter->Archive' CREATE TABLE #Temp2 ([LOGNAME] [nvarchar](20) NULL, [MESSAGE_TYPE] [int] NULL, [COMPONENT] [nvarchar](50) NULL, [LOGTIME] [nvarchar](17) NOT NULL, [SUB_SYSTEM] [nvarchar](40) NULL, [STACK_ID] [nvarchar](120) NULL, [SUBSTACK_ID] [int] NULL, [MESSAGE] [nvarchar](1800) NULL, [DETAIL] [nvarchar](1800) NULL ) INSERT INTO #Temp2 SELECT DISTINCT [LOGNAME], [MESSAGE_TYPE], [COMPONENT],cast(LEFT(LOGTIME,8) as date) AS YesterdayDate, [SUB_SYSTEM], [STACK_ID], [SUBSTACK_ID], [MESSAGE], [DETAIL] FROM [DB].[schema].[table] WHERE cast(LEFT(LOGTIME,8) as date) = cast(getdate() -1 as date) AND [DETAIL] LIKE 'USER:%' SELECT * FROM ( SELECT RIGHT(b.DETAIL, 7) AS AXAID, cast(LEFT(a.LOGTIME,8) as date) AS [DATE], b.STACK_ID, ROW_NUMBER() OVER(PARTITION by b.STACK_ID ORDER BY a.LOGTIME DESC) rn FROM #Temp1 AS a INNER JOIN #Temp2 AS b ON a.STACK_ID = b.STACK_ID WHERE a.[MESSAGE] LIKE '%Exporter->Archive' ) a WHERE rn = 1 "
oSfRs.Open sfQuery2, oSfCn
if osfrs.BOF then
Debug "There are NO results"
else
Debug "There is data in the Record Set"
end if
I am not sure if it is a syntax error with my SQL or if there it possibly because the rights of the user. Any help would be appreciate.
Please let me know if more information is needed.
For those struggling to read the SQL here is a formatted version
CREATE TABLE #Temp1 (
[LOGNAME] [nvarchar](20) NULL,
[MESSAGE_TYPE] [int] NULL,
[COMPONENT] [nvarchar](50) NULL,
[LOGTIME] [nvarchar](17) NOT NULL,
[SUB_SYSTEM] [nvarchar](40) NULL,
[STACK_ID] [nvarchar](120) NULL,
[SUBSTACK_ID] [int] NULL,
[MESSAGE] [nvarchar](1800) NULL,
[DETAIL] [nvarchar](1800) NULL
)
INSERT INTO #Temp1
SELECT DISTINCT [LOGNAME], [MESSAGE_TYPE], [COMPONENT], LOGTIME, [SUB_SYSTEM]
, [STACK_ID], [SUBSTACK_ID], [MESSAGE], [DETAIL]
FROM [DB].[schema].[table]
WHERE cast(LEFT(LOGTIME,8) as date) = cast(getdate() -1 as date)
AND [MESSAGE] LIKE '%Exporter->Archive'
CREATE TABLE #Temp2 (
[LOGNAME] [nvarchar](20) NULL,
[MESSAGE_TYPE] [int] NULL,
[COMPONENT] [nvarchar](50) NULL,
[LOGTIME] [nvarchar](17) NOT NULL,
[SUB_SYSTEM] [nvarchar](40) NULL,
[STACK_ID] [nvarchar](120) NULL,
[SUBSTACK_ID] [int] NULL,
[MESSAGE] [nvarchar](1800) NULL,
[DETAIL] [nvarchar](1800) NULL
)
INSERT INTO #Temp2 SELECT DISTINCT [LOGNAME], [MESSAGE_TYPE], [COMPONENT]
, cast(LEFT(LOGTIME,8) as date) AS YesterdayDate
, [SUB_SYSTEM], [STACK_ID], [SUBSTACK_ID], [MESSAGE], [DETAIL]
FROM [DB].[schema].[table]
WHERE cast(LEFT(LOGTIME,8) as date) = cast(getdate() -1 as date)
AND [DETAIL] LIKE 'USER:%'
SELECT *
FROM (
SELECT RIGHT(b.DETAIL, 7) AS AXAID, cast(LEFT(a.LOGTIME,8) as date) AS [DATE]
, b.STACK_ID, ROW_NUMBER() OVER(PARTITION by b.STACK_ID ORDER BY a.LOGTIME DESC) rn
FROM #Temp1 AS a
INNER JOIN #Temp2 AS b ON a.STACK_ID = b.STACK_ID
WHERE a.[MESSAGE] LIKE '%Exporter->Archive'
) a WHERE rn = 1
Resolved by comment by Lankymart.
The resolution was to add SET NOCOUNT ON to the beginning of my query.
Related
I want to import data from this SQL table:
CREATE TABLE [dbo].[TempExchangeRates](
[currency (Libellés)] [nvarchar](255) NULL,
[Currency Code] [nvarchar](255) NULL,
[2019-03] [float] NULL,
[2019-04] [float] NULL,
[2019-05] [float] NULL,
[2019-06] [float] NULL,
[2019-07] [float] NULL,
[2019-08] [float] NULL,
[2019-09] [float] NULL,
[2019-10] [float] NULL,
[2019-11] [float] NULL,
[2019-12] [float] NULL,
[2020-01] [float] NULL,
[2020-02] [float] NULL
)
With sample data:
To this one:
CREATE TABLE [dbo].[ExchangeRates]
(
[IdExchangeRate] [uniqueidentifier] NOT NULL,
[ExchangeRateCode] [nvarchar](10) NULL,
[ExchangeRatePeriodStartDate] [datetime] NULL,
[ExchangeRatePeriodEndDate] [datetime] NULL,
[ExchangeRateValue] [decimal](20, 5) NULL,
[CurrencyCode] [nvarchar](10) NULL,
)
Now I want to call a stored procedure to get fill the real table like that:
I start with stored procedure like that but I'm not sure how I could do that
------------------------- 3. Declare StartDateTable --------------------
DECLARE #StartDateExchangeRate TABLE
(
rowid INT IDENTITY(1,1) NOT NULL,
value float,
startDate date
)
-- Insert Into #StartDateExchangeRate(value, startDate)
--This finds the start dates by finding unmatched values
--SELECT id,value
-- from ExchangeRates
------------------------- 2. Declare EndDateTable --------------------
DECLARE #EndDateExchangeRate TABLE
(
EndDate date
)
Insert Into #ENdDateExchangeRate(EndDate)
--This finds the start dates by finding unmatched values
SELECT EOMONTH(startdate)
FROM #StartDateExchangeRate As ER1
-------------------------3. Join NotYet--------------------------
This question is lacking in details
Assuming the TempExchangeRates columns will vary as time goes on, here is a option that will dynamically UNPIVOT the data so it can be inserted into your final structure.
Example (or dbFiddle)
Select ExchangeRateCode = A.[Currency Code]
,ExchangeRatePeriodStartDate = period
,ExchangeRatePeriodEndDate = EOMonth(period)
,ExchangeRateValue = B.Value
,CurrencyCode = replace(upper(A.[currency (Libellés)]),' ','')
,CreatedBy = 'SomeString'
,CreatededAt = getdate()
From [TempExchangeRates] A
Cross Apply ( Select period = try_convert(date,[Key]+'-01')
,Value = try_convert(float,value)
From OpenJson((Select A.* For JSON Path,Without_Array_Wrapper ))
Where [Key] not in ('currency (Libellés)','Currency Code')
) B
Returns
I am trying to insert entire model in database using my .net application. I am using a user-defined table type.
This is my procedure and user-defined table; I am using SQL Server 2012.
CREATE TYPE [dbo].[TmpAccessRequest] AS TABLE
(
[RequestId] [int] NULL,
[RequesterID] [int] NULL,
[RequestType] [int] NULL,
[NextApprover] [int] NULL,
[RequestStatus] [varchar](100) NULL,
[Delegation] [int] NULL,
[CreatedOn] [date] NULL,
[CreatedBy] [varchar](100) NULL,
[Description] [varchar](max) NULL,
[IsSepecialRequest] [bit] NULL,
[DelegationDetailID] [int] NULL,
[IsActive] [bit] NULL,
[IsDeleted] [bit] NULL,
[ModifiedOn] [date] NULL
)
GO
CREATE PROCEDURE [dbo].[proc_SaveAccessRequest]
(#TmpAR TmpAccessRequest READONLY,
#IsUAMSRequest BIT,
#RequestID INT OUTPUT)
AS
BEGIN
INSERT INTO tblRequests (RequesterID, RequestType, NextApprover, RequestStatus,
Delegation, CreatedOn, CreatedBy, Description,
IsSepecialRequest, DelegationDetailID, IsActive, IsDeleted, ModifiedOn)
SELECT
RequesterID, RequestType, NextApprover, RequestStatus,
Delegation, CreatedOn, CreatedBy, Description,
IsSepecialRequest, DelegationDetailID, IsActive, IsDeleted, ModifiedOn
FROM
#TmpAR
SET #RequestID = SCOPE_IDENTITY()
--SET #RequestID=IDENT_CURRENT('tblRequests')
SELECT #RequestID
END
I want to check if duplicate data should not insert at the same time. So how can I do that with user-defined table type ?
Please find the changes done to your script to avoid inserting duplicate record. So i considered two columns data should be unique to avoid duplication for user understanding purpose
CREATE PROCEDURE [dbo].[proc_SaveAccessRequest]
(
#TmpAR TmpAccessRequest READONLY,
#IsUAMSRequest bit,
#RequestID int OUTPUT
)
AS
BEGIN
Insert into tblRequests
(
RequesterID
,RequestType
,NextApprover
,RequestStatus
,Delegation
,CreatedOn
,CreatedBy
,[Description]
,IsSepecialRequest
,DelegationDetailID
,IsActive
,IsDeleted
,ModifiedOn
)
SELECT
RequesterID
,RequestType
,NextApprover
,RequestStatus
,Delegation
,CreatedOn
,CreatedBy
,Description
,IsSepecialRequest
,DelegationDetailID
,IsActive
,IsDeleted
,ModifiedOn
FROM #TmpAR
WHERE NOT EXISTS ( SELECT 1
FROM tblRequests i
INNER JOIN #TmpAR o
ON i.RequesterID = o.RequesterID
AND i.RequestType = o.RequestType
AND i.NextApprover = o.NextApprover)
SELECT #RequestID = SCOPE_IDENTITY()
SELECT #RequestID
END
I have never interacted with Hash Join yet.
According to picture below, do I need an index on table tblFin_Invoices?
Or which table do I need to create index in order to avoid this Hash Join?
Is any chance I can do something to alleviate the query?
------------------------------------------------------------------------
declare
#EffDateFrom datetime = '2017-02-01',
#EffDateTo datetime= '2017-12-31'
DECLARE #ValidInvoicesTable TABLE (InvoiceNum INT PRIMARY KEY)
INSERT INTO #ValidInvoicesTable
SELECT DISTINCT INV.InvoiceNum
FROM tblFin_Invoices INV
INNER JOIN tblQuotes ON INV.QuoteID = tblQuotes.QuoteID
--INNER JOIN tblClientOffices ON tblQuotes.QuotingLocationGuid = tblClientOffices.OfficeGUID
WHERE (INV.Failed = 0)
AND dateDiff(d, #EffDateFrom, dbo.tblQuotes.EffectiveDate) >= 0
AND dateDiff(d, #EffDateTo, dbo.tblQuotes.EffectiveDate) <= 0
AND dbo.tblQuotes.LineGUID = '6E00868B-FFC3-4CA0-876F-CC258F1ED22D'
DECLARE #TempData TABLE(
[QuoteID] int,
[QuoteGUID] [uniqueidentifier] NOT NULL,
[CompanyLocationGuid] [uniqueidentifier] NULL,
[UnderwriterUserGuid] [uniqueidentifier] NULL,
[InsuredGuid] [uniqueidentifier] NULL,
[ProducerGuid] [uniqueidentifier] NULL,
[ProducerContactGuid] [uniqueidentifier] NULL,
[EffectiveDate] datetime NULL,
--[InvoiceDate] datetime NULL,
[AccountingDate] datetime NULL,
[PolicyTypeID] tinyint NOT NULL, --------------
[TransactionTypeID] varchar(2) NULL,
[QuoteStatusID] tinyint NOT NULL,
[PolicyNumber] [varchar](150) NULL,
[StateID] [char](2) NULL,
[Premium] [money] NULL,
BondRate decimal (5,4) NULL,
[PenalLiability] [money] NULL,
[CompanyCommission] decimal(3,2) NULL
)
INSERT INTO #TempData
SELECT
INV.QuoteID,
tblQuotes.QuoteGUID,
tblQuotes.CompanyLocationGuid,
tblQuotes.UnderwriterUserGuid,
tblSubmissionGroup.InsuredGuid,
tblProducerLocations.ProducerGUID,
tblQuotes.ProducerContactGuid,
INV.EffectiveDate,
INV.InvoiceDate,
--dbo.CalcAccountingDate(tblQuotes.QuoteStatusID,INV.invoicedate,INV.effectivedate, tblQuotes.EndorsementEffective) AccountingDate,
tblQuotes.PolicyTypeID,
tblQuotes.TransactionTypeID,
tblQuotes.QuoteStatusID,
tblQuotes.PolicyNumber,
tblQuotes.StateID,
(SELECT ISNULL(SUM(tblFin_InvoiceDetails.AmtBilled), 0)
FROM tblFin_InvoiceDetails
WHERE (tblFin_InvoiceDetails.ChargeType = 'P')
AND (tblFin_InvoiceDetails.InvoiceNum = INV.InvoiceNum))
AS Premium,
[Dynamic_Data_SuretyPRC].BondRate,
[Dynamic_Data_SuretyPRC].BondAmount,
[Dynamic_Data_SuretyPRC].CompanyComm
FROM tblFin_Invoices INV
INNER JOIN tblQuotes ON INV.QuoteID = tblQuotes.QuoteID
INNER JOIN tblProducerLocations ON INV.ProducerLocationGUID = tblProducerLocations.ProducerLocationGUID
INNER JOIN tblSubmissionGroup ON tblQuotes.SubmissionGroupGuid = tblSubmissionGroup.SubmissionGroupGUID
LEFT JOIN [dbo].[Dynamic_Data_SuretyPRC] ON Dynamic_Data_SuretyPRC.QuoteGUID = tblQuotes.QuoteGUID
WHERE INV.InvoiceNum IN (SELECT * FROM #ValidInvoicesTable)
ORDER BY INV.InvoiceDate
--select * from #TempData
All the tables you use in the first query for #ValidInvoicesTable are also in the second query. Instead of using #ValidInvoicesTable, use the WHERE conditions from that SELECT and replace the WHERE condition in the second SELECT statement.
I'd also use BETWEEN instead of two statements for the date comparison, to get the same result you'll need to CAST/CONVERT the EffectiveDate, if the DateTime field actually contains Time.
I'd also make a join out of tblFin_InvoiceDetails.
I assume that you are going to use the #TempData table for something other the just a SELECT statement. If I'm wrong, you should remove the DECLARE and INSERT INTO regarding #TempData table completely.
Below is my suggestion.
declare
#EffDateFrom datetime = '2017-02-01',
#EffDateTo datetime= '2017-12-31'
DECLARE #TempData TABLE(
[QuoteID] int,
[QuoteGUID] [uniqueidentifier] NOT NULL,
[CompanyLocationGuid] [uniqueidentifier] NULL,
[UnderwriterUserGuid] [uniqueidentifier] NULL,
[InsuredGuid] [uniqueidentifier] NULL,
[ProducerGuid] [uniqueidentifier] NULL,
[ProducerContactGuid] [uniqueidentifier] NULL,
[EffectiveDate] datetime NULL,
--[InvoiceDate] datetime NULL,
[AccountingDate] datetime NULL,
[PolicyTypeID] tinyint NOT NULL, --------------
[TransactionTypeID] varchar(2) NULL,
[QuoteStatusID] tinyint NOT NULL,
[PolicyNumber] [varchar](150) NULL,
[StateID] [char](2) NULL,
[Premium] [money] NULL,
BondRate decimal (5,4) NULL,
[PenalLiability] [money] NULL,
[CompanyCommission] decimal(3,2) NULL
)
INSERT INTO #TempData
SELECT
INV.QuoteID,
tblQuotes.QuoteGUID,
tblQuotes.CompanyLocationGuid,
tblQuotes.UnderwriterUserGuid,
tblSubmissionGroup.InsuredGuid,
tblProducerLocations.ProducerGUID,
tblQuotes.ProducerContactGuid,
INV.EffectiveDate,
INV.InvoiceDate,
tblQuotes.PolicyTypeID,
tblQuotes.TransactionTypeID,
tblQuotes.QuoteStatusID,
tblQuotes.PolicyNumber,
tblQuotes.StateID,
SUM(ISNULL(tblDetailed.AmtBilled, 0)) AS Premium,
[Dynamic_Data_SuretyPRC].BondRate,
[Dynamic_Data_SuretyPRC].BondAmount,
[Dynamic_Data_SuretyPRC].CompanyComm
FROM tblFin_Invoices INV
INNER JOIN tblQuotes ON INV.QuoteID = tblQuotes.QuoteID
INNER JOIN tblProducerLocations ON INV.ProducerLocationGUID = tblProducerLocations.ProducerLocationGUID
INNER JOIN tblSubmissionGroup ON tblQuotes.SubmissionGroupGuid = tblSubmissionGroup.SubmissionGroupGUID
LEFT JOIN [dbo].[Dynamic_Data_SuretyPRC] ON Dynamic_Data_SuretyPRC.QuoteGUID = tblQuotes.QuoteGUID
LEFT JOIN tblFin_InvoiceDetail tblDetail ON tblDetail.InvoiceNum = INV.InvoiceNum AND tblDetail.ChargeType = 'P'
WHERE
INV.Failed = 0
AND CAST(dbo.tblQuotes.EffectiveDate as date) BETWEEN #EffDateFrom AND #EffDateTo
AND dbo.tblQuotes.LineGUID = '6E00868B-FFC3-4CA0-876F-CC258F1ED22D'
GROUP BY INV.QuoteID,
tblQuotes.QuoteGUID,
tblQuotes.CompanyLocationGuid,
tblQuotes.UnderwriterUserGuid,
tblSubmissionGroup.InsuredGuid,
tblProducerLocations.ProducerGUID,
tblQuotes.ProducerContactGuid,
INV.EffectiveDate,
INV.InvoiceDate,
tblQuotes.PolicyTypeID,
tblQuotes.TransactionTypeID,
tblQuotes.QuoteStatusID,
tblQuotes.PolicyNumber,
tblQuotes.StateID,
[Dynamic_Data_SuretyPRC].BondRate,
[Dynamic_Data_SuretyPRC].BondAmount,
[Dynamic_Data_SuretyPRC].CompanyComm
ORDER BY INV.InvoiceDate
I'm a rookie to SQL Server. I'm using SQL Server 2008 R2. I have created two tables called adding_hanger and allot as follows
CREATE TABLE [dbo].[adding_hanger]
(
[End_Id] [bigint] IDENTITY(1,1) NOT NULL,
[Hanger_Location] [char](10) NOT NULL,
[Hanger_Capacity] [int] NOT NULL,
[Hanger_Id] AS ((CONVERT([varchar](100),substring([Hanger_Location],(1),(3)),0)+'101')+CONVERT([varchar](100),[End_Id],0)) PERSISTED NOT NULL,
[Manager_Name] [varchar](15) NOT NULL,
[Manager_Id] AS ((CONVERT([varchar](4),substring([Social_Security_No],(8),(4)),0)+'31')+CONVERT([varchar](100),[End_Id],0)) PERSISTED NOT NULL,
[Manager_Password] AS ((CONVERT([varchar](3),substring([Manager_Name],(1),(3)),0)+'#')+CONVERT([varchar](3),substring([Hanger_Location],(1),(3)),0)),
[Social_Security_No] [varchar](15) NOT NULL,
[Date_of_Birth] [datetime] NOT NULL,
[Gender] [varchar](8) NOT NULL,
[Mobile_No] [varchar](50) NOT NULL,
[Email_Address] [varchar](30) NOT NULL,
[House_No] [varchar](10) NOT NULL,
[Address_Line_1] [varchar](30) NOT NULL,
[Address_id] AS ((CONVERT([varchar](100),substring([City],(1),(3)),0)+'31')+CONVERT([varchar](100),[End_Id],0)) PERSISTED NOT NULL,
[City] [char](15) NOT NULL,
[State] [char](15) NOT NULL,
[Country] [char](15) NOT NULL,
[Pin_No] [int] NOT NULL
)
CREATE TABLE [dbo].[allot]
(
[Fromdate] [datetime] NULL,
[todate] [datetime] NULL,
[hangarlocation] [char](10) NULL,
[hangarno] [varchar](100) NULL,
[planeid] [varchar](100) NULL
)
How do I fetch the details of the available hangers that are not allotted within a given range of from and to dates given as input and also not exceeding the capacity of the hanger if allocated already?
First, your spelling of 'hangar' is inconsistent and should be addressed.
I'm assuming that the hangar capacity represents how many allots you can store in that hangar? If so, the hangar capacity might vary over a given timeframe as allots are added/removed (according to FromDate and ToDate), so your question isn't clear. If you want a hangar that definitely has a space free over a given period, I would use:
declare #from_date datetime, #end_date datetime, #i int
-- Set your start and end dates (replace the dates below with the correct ones)
set #from_date = '2016-07-01'
set #to_date = '2016-07-31'
set #i = 1 -- counter
-- Create a table of dates
select #from_date as date into #dates
while dateadd(day,#i,#from_date) <= #to_date
begin
insert into #dates values (dateadd(day,#i,#from_date))
end
-- Create table of date, hangar_id, hangar_capacity
select date, hangar_id, hangar_capacity
into #dates_by_hangar
from adding_hangar
inner join #dates on 1 = 1
-- Table showing hangars with at least one free space on every date in the range
select hangar_id from (
-- 2. Table showing hangar space free on each date
select a.*, a.hanger_capacity - isnull(b.allots_in_hangar,0) as hangar_space_free
from #dates_by_hangar a
left outer join (
-- 1. Table showing number of allots in each hangar on a given date
select date, hangar_no, sum(case when b.hangar_no is not null then 1 else 0 end) as allots_in_hangar
from #dates a
left outer join allot b
on a.date between b.fromdate and b.todate
group by date, hangar_no) b
on a.hangar_id = b.hangar_no
and a.date = b.date
)
group by hangar_no
having max(hangar_space_free) >= 1
SELECT ah.* from [adding_hanger] AS ah
INNER JOIN [allot] ON allot.hangarlocation = ah.Hanger_Location
WHERE (allot.Fromdate < <input_from_date> OR allot.todate > <input_to_date>)
OR (allot.Fromdate >= <input_from_date> AND allot.todate <= <input_to_date> AND ah.Hanger_Capacity <= <input_capacity>)
I have a table with two date columns, both allow nulls.
if FileDate is not null then AsOfDate needs to equal (FileDate - Offset) where Offset is a integer column with a default of zero.
Here is my table def:
CREATE TABLE [import].[CMAR_GLXXXX](
[FileDate] [date] NULL,
[LoadDTM] [date] NULL,
[AsOfDate] [date] NULL,
[AccountNumber] [varchar](50) NOT NULL,
[CostCenter] [varchar](50) NOT NULL,
[OffSet] [int] default (0) NOT NULL,
[Value] [decimal](10,2) NOT NULL
) ON [PRIMARY]
I tried using the following:
(case when [File] IS NULL then NULL else dateadd(day,(-1 * [Offset]),[FileDate]) end)
Unfortunately the computed column error dialog doesn't display much help in troubleshooting the expression.
Any ideas?
A case expression is perfectly valid here but not needed for your desired output. Let sql server handle NULLS naturally.
dateadd(day,(-1 * x),[d1])
--EDIT--
To demonstrate here is a table definition. Seems this does exactly what you are looking for.
create table #Something
(
x int
, d1 datetime
, compCol as dateadd(day, (-1 * x), [d1])
)
insert #Something
select 3, null union all
select 4, '2016-01-01'
select *
from #Something
I am assuming your expression is correct. just use correct syntax for case.
CREATE TABLE CMAR_GLXXXX(
[FileDate] [date] NULL,
[LoadDTM] [date] NULL,
[AsOfDate] [date] NULL,
[AccountNumber] [varchar](50) NOT NULL,
[CostCenter] [varchar](50) NOT NULL,
[OffSet] [int] default (0) NOT NULL,
[Value] [decimal](10,2) NOT NULL
)
select
(case when [FileDate] IS NULL then NULL else dateadd(day,(-1 * [OffSet]),[FileDate]) end)
from CMAR_GLXXXX