I created a stored procedure which works perfectly. In an effort to convert it to a function in order to output tables for being used in other code, I created a multi-statement function.
I cannot use temporary tables so i now declare them as table variables but i get the errors bellow. I tried everything i can imagine and searched but either i am not doing it right or its not supported.
Declaring 3 tables as variables (instead of temporary tables in procedure)
I keep getting this error:
Msg 137, Level 16, State 1, Procedure _SLA_report_funct, Line ...
Must declare the scalar variable "#SupCarsSche".
CODE below:
USE DatabaseName
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: xxxxxxxxxxx
-- Create date:
-- Description:
-- =============================================
ALTER FUNCTION dbo._SLA_report_funct
(
-- Add the parameters for the function here
#Interval varchar(20),
#Starting_Datetime_offset int = 0,
#Trip_or_Day varchar(4)
)
RETURNS
#Table_Var TABLE
(
-- Add the column definitions for the TABLE variable here
TrainNumber int,
SerDate datetime,
First varchar(50),
Last varchar(50),
CusCarNumber int,
Fleet varchar(5),
Scheduled_Car bigint,
Depart varchar(50),
DepartTime varchar(50),
Arrive varchar(50),
ArriveTime varchar(50),
NodeOD int,
Caption nvarchar(255),
Trip_Availability real,
Trp_Availability_Count real,
Duration int
)
AS
BEGIN
-- Fill the table variable with the rows for your result set
DECLARE #SupCarsSche table
(
TrainNumber int,
SerDate datetime,
First varchar(50),
Last varchar(50),
CusCarNumber int,
Fleet varchar(5),
Scheduled_Car bigint,
Depart varchar(50),
DepartTime varchar(50),
Arrive varchar(50),
ArriveTime varchar(50)
)
DECLARE #SQLTemp varchar(MAX)
INSERT #SupCarsSche
SELECT
vsch.TrainNumber,
vsch.SerDate,
vsch.First,
vsch.Last,
vsch. CusCarNumber,
vsch.Fleet,
vsch.CarNumber AS Scheduled_Car,
vsch.Depart,
vsch.DepartTime,
vsch.Arrive,
vsch.ArriveTime
FROM _viaschedule5 AS vsch
RIGHT JOIN _supported_cars as supc ON vsch.CarNumber=supc.CarNumber
WHERE
((#Interval='MONTH') AND (datediff(MONTH, CAST(vsch.SerDate as DATE),(CAST(GETDATE() as DATE)))=#Starting_Datetime_offset) AND
(vsch.CarNumber LIKE '73%' OR NOT (vsch.CusCarNumber='')))
OR
((#Interval='DAY') AND (datediff(DAY, CAST(vsch.SerDate as DATE),(CAST(GETDATE() as DATE)))=#Starting_Datetime_offset) AND
(vsch.CarNumber LIKE '73%' OR NOT (vsch.CusCarNumber='')))
DECLARE #TripAvail table
(
NodeID int,
Caption nvarchar(255),
Trip_Availability real,
Trp_Availability_Count real,
SerDate datetime,
TrainNumber int,
Scheduled_Car bigint,
DepartTime varchar(50),
ArriveTime varchar(50),
Duration int
)
INSERT #TripAvail
SELECT
Nodes.NodeID,
Nodes.Caption AS Caption,
AVG(ResponseTime_Detail.Availability) AS Trip_Availability,
COUNT(ResponseTime_Detail.Availability) AS Trp_Availability_Count,
#SupCarsSche.SerDate,
#SupCarsSche.TrainNumber,
#SupCarsSche.Scheduled_Car,
#SupCarsSche.DepartTime,
#SupCarsSche.ArriveTime,
CASE
WHEN
(Datediff(MINUTE,CAST(#SupCarsSche.DepartTime as TIME),CAST(#SupCarsSche.ArriveTime as TIME))>0)
THEN
Datediff(MINUTE,CAST(#SupCarsSche.DepartTime as TIME),CAST(#SupCarsSche.ArriveTime as TIME))
ELSE
CAST ((24*60)-(DATEPART(hour, #SupCarsSche.DepartTime) * 60) - (DATEPART(minute, #SupCarsSche.DepartTime) * 1)+
(DATEPART(hour, #SupCarsSche.ArriveTime) * 60) + (DATEPART(minute, #SupCarsSche.ArriveTime) * 1)AS INT)
END AS Duration
FROM #SupCarsSche
LEFT JOIN Nodes ON (#SupCarsSche.Scheduled_Car = Nodes.Coach_ID)
LEFT JOIN ResponseTime_Detail ON ((Nodes.NodeID=ResponseTime_Detail.NodeID) AND (
((ResponseTime_Detail.DateTime BETWEEN (#SupCarsSche.SerDate+#SupCarsSche.DepartTime) AND (#SupCarsSche.SerDate+#SupCarsSche.ArriveTime))AND #SupCarsSche.DepartTime<#SupCarsSche.ArriveTime) OR
((ResponseTime_Detail.DateTime BETWEEN (#SupCarsSche.SerDate+#SupCarsSche.DepartTime) AND (DATEADD(DAY,1,#SupCarsSche.SerDate+#SupCarsSche.ArriveTime)))AND #SupCarsSche.DepartTime>#SupCarsSche.ArriveTime )))
GROUP BY #SupCarsSche.TrainNumber,Nodes.NodeID,#SupCarsSche.SerDate,#SupCarsSche.Scheduled_Car,Nodes.Caption,
#SupCarsSche.DepartTime, #SupCarsSche.ArriveTime,
CASE WHEN (
Datediff(MINUTE,CAST(#SupCarsSche.DepartTime as TIME),CAST(#SupCarsSche.ArriveTime as TIME))>0)
THEN
Datediff(MINUTE,CAST(#SupCarsSche.DepartTime as TIME),CAST(#SupCarsSche.ArriveTime as TIME))
ELSE
CAST ((24* 60)-(DATEPART(hour, #SupCarsSche.DepartTime) * 60) - (DATEPART(minute, #SupCarsSche.DepartTime) * 1)+(DATEPART(hour, #SupCarsSche.ArriveTime) * 60) + (DATEPART(minute, #SupCarsSche.ArriveTime) * 1)AS INT)
END
RETURN
END
It looks like when I use table variables, I need to add
FROM #SupCarsSche AS SCSH
After that, I use SCSH everywhere instead of the variable name.
This seems to resolve the issue.
Related
I built a wrapper function that currently just calls another table-valued Function but it just added a huge amount to the execution time as Client processing time. Is there a faster way to do this?
Without wrapper:
With Wrapper:
Wrapper function:
CREATE FUNCTION [console].[getCalculosRequisita]
(
#Disponivel BIGINT,
#mediaDiaria float,
#DiasStockArtigo INT,
#DiasAntes INT,
#SaidasPorMes float,
#QtdEncomendada2Meses BIGINT,
#StockAtual BIGINT,
#QtdRequisitada BIGINT,
#caixaMinima INT
)
RETURNS #tbl TABLE
(
DiasAteRotura INT,
AcaoRequisita varchar(10),
Aconselhada BIGINT
)
AS
BEGIN
--future configuration check
--future log input
INSERT INTO #tbl SELECT DiasAteRotura, AcaoRequisita,Aconselhada
FROM [cartridge].[getCalculosRequisitaTSQL]
(
#Disponivel ,
#mediaDiaria ,
#DiasStockArtigo ,
#DiasAntes ,
#SaidasPorMes ,
#QtdEncomendada2Meses ,
#StockAtual ,
#QtdRequisitada ,
#caixaMinima
)
--future log output
RETURN
END
GO
Do it as an inline TVF, which is much, much faster:
CREATE FUNCTION [console].[getCalculosRequisita]
(
#Disponivel BIGINT,
#mediaDiaria float,
#DiasStockArtigo INT,
#DiasAntes INT,
#SaidasPorMes float,
#QtdEncomendada2Meses BIGINT,
#StockAtual BIGINT,
#QtdRequisitada BIGINT,
#caixaMinima INT
)
RETURNS TABLE -- WITH SCHEMABINDING -- preferable, but then you can't change the underlying function
(
DiasAteRotura INT,
AcaoRequisita varchar(10),
Aconselhada BIGINT
)
AS RETURN
(SELECT DiasAteRotura, AcaoRequisita, Aconselhada
FROM [cartridge].[getCalculosRequisitaTSQL]
(
#Disponivel ,
#mediaDiaria ,
#DiasStockArtigo ,
#DiasAntes ,
#SaidasPorMes ,
#QtdEncomendada2Meses ,
#StockAtual ,
#QtdRequisitada ,
#caixaMinima
) AS t
);
GO
Obviously, if you do this then you cannot do any other inserts. In any case logging would be impossible, so I'm not sure what you were planning on doing.
You have not given the code for the underlying function. Perhaps that can be done as an iTVF also.
I really appreciate the replies. They were insightfull and I will upvote them all. I just post some code here for the sharing. Happy to hear your thougts if you have suggestions.
What I really wanted was to run Python from a View, I had to go complety for another direction and I think performance just went down the drain.
It seems Python runs only from Stored Procedures... so had to go for a OPENROWSET (!?) to have it as a VIEW. Not pretty, example below:
DROP PROC IF EXISTS PythonExample;
GO
CREATE PROC PythonExample
AS
BEGIN
set nocount on
SET FMTONLY OFF
DROP TABLE [dbo].[MyRows]
CREATE TABLE [dbo].[MyRows](
[RowNum] [int] NULL
) ON [PRIMARY]
INSERT INTO [MyRows]
([RowNum])
VALUES
(1),
(2)
DECLARE #tbl1 TABLE
(
COL1 INT,
COL2 INT
)
INSERT INTO #tbl1
---ATTENTION Identing is important for Python code...
EXEC sp_execute_external_script #language =N'Python',
#script=N'
import pandas as pd
df= MyInput
df["newCol"]= df["RowNum"]*2
MyOutput = df;
',
#input_data_1_name = N'MyInput',
#input_data_1 =N'SELECT [RowNum] FROM [MyRows]', --- it seems it cannot handle a temp table
#output_data_1_name =N'MyOutput'
--WITH RESULT SETS ((MyColName int, MyColName2 int));
SELECT * FROM #tbl1
END;
GO
DROP VIEW IF EXISTS ViewExample;
GO
CREATE VIEW ViewExample
AS
SELECT * FROM OPENROWSET('SQLNCLI', 'Server=localhost;Trusted_Connection=yes;', 'exec [dbo].[PythonExample]')
GO
SELECT * FROM ViewExample
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.
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.
I have a table to which I added a new column, as such:
ALTER TABLE [Invoice].[Invoice] ADD [DaysToPay] int
GO
ALTER TABLE [Invoice].[Invoice] ADD CONSTRAINT [DF_Invoice_DaysToPay] DEFAULT ((30)) FOR [DaysToPay]
GO
UPDATE [Invoice].[Invoice] SET [DaysToPay] = 30
GO
ALTER TABLE [Invoice].[Invoice] ALTER COLUMN [DaysToPay] int NOT NULL
GO
If I now do SELECT * FROM [Invoice].[Invoice] I get an Invalid column name 'DaysToPay' error. I get this error whether I run the statement through SSMS or any other means (via code).
The same error occurs with or without the column when I select specific columns. e.g. SELECT [InvoiceID] FROM [Invoice].[Invoice].
I have closed SSMS and restarted the SQL service. Still the same error.
The column was added under the same user that is getting the error and that same user is the owner of the schema.
Both these statements return 0 rows:
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'DaysToPay'
SELECT *
FROM sys.columns
WHERE Name = N'DaysToPay'
I've tried Ctrl + Shift + R but I don't think it's a SSMS thing and it made no difference.
The database is not replicated.
I ran a DBCC OPENTRAN are there were none active.
I have since removed the column (manually using the designer in SSMS) and I still get the same error. The table shows correctly in the SSMS designer (as it did prior to me manually removing it).
Any ideas other than dropping and re-creating the table?
EDIT:
The rest of the script that was run is as follows (I have removed certain columns so as not to identify):
ALTER PROCEDURE [Invoice].[Invoice_Save] (
#InvoiceID int,
#TypeID int,
#InvoiceNumber int,
#InvoiceDate datetime,
#DatePaid datetime,
#PaymentEnteredBy int,
#AmountPaid float,
#PaymentTypeID int,
#HasVAT bit,
#VATRate float,
#TranslationPercentageCharge float,
#IsVoid bit,
#VoidDate datetime,
#VoidBy int,
#DateSent datetime,
#SentBy int,
#PurchaseOrderNumber varchar(100),
#BillingContact varchar(255),
#BillingAddress varchar(MAX),
#BillingContactEmail nvarchar(255),
#BillingContactTelNo varchar(50),
#Notes varchar(MAX),
#CompanyID int,
#DaysToPay int,
#DateCreated datetime,
#CreatedBy int,
#LastUpdated datetime,
#LastUpdatedBy int
)
AS
IF NOT EXISTS (SELECT * FROM [Invoice].[Invoice] WHERE [InvoiceID] = #InvoiceID)
BEGIN
INSERT INTO [Invoice].[Invoice] ([TypeID], [InvoiceNumber], [InvoiceDate], , [DatePaid], [PaymentEnteredBy], [AmountPaid], [PaymentTypeID], [HasVAT], [VATRate], [TranslationPercentageCharge], [IsVoid], [VoidDate], [VoidBy], [DateSent], [SentBy], [PurchaseOrderNumber], [BillingContact], [BillingAddress], [BillingContactEmail], [BillingContactTelNo], [Notes], [CompanyID], [DaysToPay], [DateCreated], [CreatedBy], [LastUpdated], [LastUpdatedBy])
VALUES (#TypeID, #InvoiceNumber, #InvoiceDate, #DatePaid, #PaymentEnteredBy, #AmountPaid, #PaymentTypeID, #HasVAT, #VATRate, #TranslationPercentageCharge, #IsVoid, #VoidDate, #VoidBy, #DateSent, #SentBy, #PurchaseOrderNumber, #BillingContact, #BillingAddress, #BillingContactEmail, #BillingContactTelNo, #Notes, #CompanyID, #DaysToPay, #DateCreated, #CreatedBy, #LastUpdated, #LastUpdatedBy)
SELECT MAX([InvoiceID]) AS MaxID FROM [Invoice].[Invoice]
END
ELSE
UPDATE [Invoice].[Invoice]
SET [TypeID] = #TypeID,
[InvoiceNumber] = #InvoiceNumber,
[InvoiceDate] = #InvoiceDate,
[DatePaid] = #DatePaid,
[PaymentEnteredBy] = #PaymentEnteredBy,
[AmountPaid] = #AmountPaid,
[PaymentTypeID] = #PaymentTypeID,
[HasVAT] = #HasVAT,
[VATRate] = #VATRate,
[TranslationPercentageCharge] = #TranslationPercentageCharge,
[IsVoid] = #IsVoid,
[VoidDate] = #VoidDate,
[VoidBy] = #VoidBy,
[DateSent] = #DateSent,
[SentBy] = #SentBy,
[PurchaseOrderNumber] = #PurchaseOrderNumber,
[BillingContact] = #BillingContact,
[BillingAddress] = #BillingAddress,
[BillingContactEmail] = #BillingContactEmail,
[BillingContactTelNo] = #BillingContactTelNo,
[Notes] = #Notes,
[CompanyID] = #CompanyID,
[DaysToPay] = #DaysToPay,
[DateCreated] = #DateCreated,
[CreatedBy] = #CreatedBy,
[LastUpdated] = #LastUpdated,
[LastUpdatedBy] = #LastUpdatedBy
WHERE [InvoiceID] = #InvoiceID
GO
I'm looking for suggestions on how to go about doing something that I am fairly certain that I should be able to do with SSIS.
I have two databases and I am updating Table B from Table A but as I do this I want to with ever successful write to Table B write some additional information to a log table back in the originating database. (See Illustration)
I'm not sure what control(s) I would use to accomplish this but suspect that it can be done inside of SSIS.
Use an OLEDB Transformation to do the UPDATE to table B, and then follow that with a Destination that writes to the log table.
After suggestions by Ivan Starostin and others on the board, I've opt'd to abandon using SSIS for doing this process and use stored procedures called from the code behind in the web page to perform this functionality. I'm including example of the insert process SP below as I'm working on the remainder but would like to close this question. Thanks to Ivan and all for your input. SSIS simply wasn't the best tool for this situation. It was much cleaner using SP as I found out.
USE [CInTracDB]
GO
/******** Object: StoredProcedure [dbo].[usp_InsertNewAssets] Script Date: 12/15/2016 3:00:00 PM *****/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Ken Carter>
-- Create date: <Dec 15, 2016>
-- Description: <Input Fields from Updates table, Insert all NEW records into CMDB.dbo.cmdb_assets, then copy record from
-- Updates to CInTracDB.dbo.Update_log, then Delete Record from Updates,
-- Return only sucesss / fail signal.
-- =============================================
CREATE PROCEDURE [dbo].[usp_InsertNewAssets](
#CAssetID as bigint,
#SubmitBy as varchar(50),
#SubmitDT as datetime,
#ApproveBy as varchar(50),
#Approved as char(10),
#ApprovedDT as datetime,
#Imported as char(10),
#ImportDT as datetime,
#AssetID as bigint,
#AssetType as int,
#AssetName as varchar(128),
#AssetShortDesc as varchar(50),
#AssetLongDesc as varchar(200),
#AssetAddNotes as varchar(254),
#AssetManuf as varchar(50),
#AssetModel as varchar(50),
#AssetTag as varchar(20),
#AssetAcqDate as datetime,
#AssetDTAssetID as varchar(20),
#AssetLocGrp as varchar(10),
#AssetLoc1 as varchar(8),
#AssetLoc2 as varchar(8),
#AssetLoc3 as varchar(8),
#AssetParent as bigint,
#AssetStatus as int,
#AssetPropType as int,
#AssetPrimUser as varchar(20),
#AssetEntered as datetime,
#AssetEnteredBy as varchar(50),
#AssetOwner as varchar(50),
#AssetCompany as varchar(10),
#AssetPriIPAddr as varchar(15),
#AssetPriMACAddr as varchar(17),
#AssetPriOS as varchar(20),
#AssetPriOSSP as varchar(20),
#AssetNotes as varchar(500),
#AssetAdminGrp as varchar(100),
#AssetSerialNum as varchar(75),
#AssetOperType as int,
#AssetOperStatus as int
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #AssetFACL as bit = 0
DECLARE #AssetStatVer as bit = 0
BEGIN
INSERT INTO CMDB.dbo.cmdb_assets (AssetType, AssetName, AssetShortDesc, AssetLongDesc, AssetAddNotes, AssetManuf,
AssetModel, AssetTag, AssetAcqDate, AssetDTAssetID, AssetLocGrp, AssetLoc1, AssetLoc2, AssetLoc3, AssetParent,
AssetStatus, AssetPropType, AssetPrimUser, AssetEntered, AssetEnteredBy, AssetOwner, AssetCompany, AssetPriIPAddr,
AssetPriMACAddr, AssetPriOS, AssetPriOSSP, AssetNotes, AssetAdminGrp, AssetSerialNum, AssetOperType,
AssetOperStatus, AssetFACL, AssetStatVer)
SELECT AssetType, AssetName, AssetShortDesc, AssetLongDesc, AssetAddNotes, AssetManuf, AssetModel, AssetTag,
AssetAcqDate, AssetDTAssetID, AssetLocGrp, AssetLoc1, AssetLoc2, AssetLoc3, AssetParent, AssetStatus, AssetPropType,
AssetPrimUser, AssetEntered, AssetEnteredBy, AssetOwner, AssetCompany, AssetPriIPAddr, AssetPriMACAddr, AssetPriOS,
AssetPriOSSP, AssetNotes, AssetAdminGrp, AssetSerialNum, AssetOperType, AssetOperStatus
FROM Updates
WHERE AssetID > 0
END
BEGIN
Insert INTO Update_log (CAssetID, SubmitBy, SubmitDT, ApproveBy, Approved, ApprovedDT, Imported, ImportDT, AssetID,
AssetType, AssetName, AssetShortDesc, AssetLongDesc, AssetAddNotes, AssetManuf, AssetModel, AssetTag, AssetAcqDate,
AssetDTAssetID, AssetLocGrp, AssetLoc1, AssetLoc2, AssetLoc3, AssetParent, AssetStatus, AssetPropType,
AssetPrimUser, AssetEntered, AssetEnteredBy, AssetOwner, AssetCompany, AssetPriIPAddr, AssetPriMACAddr, AssetPriOS,
AssetPriOSSP, AssetNotes, AssetAdminGrp, AssetSerialNum, AssetOperType, AssetOperStatus)
SELECT AssetType, AssetName, AssetShortDesc, AssetLongDesc, AssetAddNotes, AssetManuf, AssetModel, AssetTag,
AssetAcqDate, AssetDTAssetID, AssetLocGrp, AssetLoc1, AssetLoc2, AssetLoc3, AssetParent, AssetStatus, AssetPropType,
AssetPrimUser, AssetEntered, AssetEnteredBy, AssetOwner, AssetCompany, AssetPriIPAddr, AssetPriMACAddr, AssetPriOS,
AssetPriOSSP, AssetNotes, AssetAdminGrp, AssetSerialNum, AssetOperType, AssetOperStatus
FROM Updates
WHERE AssetID > 0
END
BEGIN
DELETE FROM Updates
WHERE (AssetID > 0)
END
END
GO