i want to insert the default values, if the values i gave him are 0 or ''
ALTER procedure [dbo].[altaemp]
#id_emp int,
#nom_emp varchar(100),
#lnom_emp varchar(100),
#l2nom_emp varchar(100),
#id_type int,
#id_supervisor int,
#correo varchar(50),
#id_area int
as
begin
if #id_supervisor = 0 (select #id_supervisor = ?? )
if #correo = '' (select #correo = ??)
INSERT INTO [dbo].[empleados]
([id_emp]
,[nom_emp]
,[lnom_emp]
,[l2nom_emp]
,[id_type]
,[id_supervisor]
,[correo]
,[id_area])
VALUES
(#id_emp,
#nom_emp,
#lnom_emp,
#l2nom_emp,
#id_type,
#id_supervisor,
#correo,
#id_area)
return
end
i have tried equals the variables to null or default without success
To handle these 2 cases you can add the following decision statements, replacing ?? with your replacement value:
IF LEN(#correo) = 0 SET #correo = ??
IF #id_supervisor = 0 SET #id_supervisor = ??
I like to use a COALESCE with a NULLIF inside it to achieve this.
SELECT #id_supervisor = COALESCE(NULLIF(#id_supervisor,0),[DEFAULT VALUE])
,#correo = COALESCE(NULLIF(#correo ,' '),[DEFAULT VALUE])
There are multiple options for handling this scenario. If they are truly default values, you can simply pass null into the stored procedure and define the procedure like this:
ALTER procedure [dbo].[altaemp]
#id_emp int,
#nom_emp varchar(100),
#lnom_emp varchar(100),
#l2nom_emp varchar(100),
#id_type int,
#id_supervisor int = <default supervisor id>,
#correo varchar(50) = <default correo>,
#id_area int
as
begin
INSERT INTO [dbo].[empleados]
([id_emp]
,[nom_emp]
,[lnom_emp]
,[l2nom_emp]
,[id_type]
,[id_supervisor]
,[correo]
,[id_area])
VALUES
(#id_emp,
#nom_emp,
#lnom_emp,
#l2nom_emp,
#id_type,
#id_supervisor,
#correo,
#id_area)
return
end
Alternatively, if there is a decision that has to be made, you can replace your logic with case logic which would look similar to this:
ALTER procedure [dbo].[altaemp]
#id_emp int,
#nom_emp varchar(100),
#lnom_emp varchar(100),
#l2nom_emp varchar(100),
#id_type int,
#id_supervisor int = <default supervisor id>,
#correo varchar(50) = <default correo>,
#id_area int
as
begin
INSERT INTO [dbo].[empleados]
([id_emp]
,[nom_emp]
,[lnom_emp]
,[l2nom_emp]
,[id_type]
,[id_supervisor]
,[correo]
,[id_area])
Select #id_emp,
#nom_emp,
#lnom_emp,
#l2nom_emp,
#id_type,
CASE WHEN #id_supervisor = 0 THEN <Default SupervisorId> ELSE #id_supervisor END,
CASE WHEN #correo= '' THEN <Default correo> ELSE #correo END,
#id_area
return
end
Since you can pass null instead of 0 and '', then you can try this:
ALTER procedure [dbo].[altaemp]
#id_emp int,
#nom_emp varchar(100),
#lnom_emp varchar(100),
#l2nom_emp varchar(100),
#id_type int,
#id_supervisor int=100, -- Default value=100
#correo varchar(50)='my Default Value', -- Default Value
#id_area int
as
begin
INSERT INTO [dbo].[empleados]
([id_emp]
,[nom_emp]
,[lnom_emp]
,[l2nom_emp]
,[id_type]
,[id_supervisor]
,[correo]
,[id_area])
VALUES
(#id_emp,
#nom_emp,
#lnom_emp,
#l2nom_emp,
#id_type,
#id_supervisor,
#correo,
#id_area)
return
end
So, you can call the procedure like this:
EXEC [dbo].[altaemp]
#id_emp = yourValue,
#nom_emp = yourValue,
#lnom_emp = yourValue,
#l2nom_emp = yourValue,
#id_type = yourValue,
#id_supervisor = null, -- Specify Null or remove parameter
#correo = null, -- Specify Null or remove parameter
#id_area = yourValue
Related
I have a Stored Procedure with a JSON in input ,Is it possible to use the JSON as input for a stored procedure? how could i do that ?
CREATE PROCEDURE [warm].[stored _table]
(
#Json NVARCHAR(MAX)
)
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
BEGIN
WITH JsonToTable AS
(
SELECT * FROM OPENJSON (#Json) WITH (
[type] [nvarchar](100),
[source] [nvarchar](38),
[time] [nvarchar](28),
[ID] [varchar](50) '$.data.ID',
[RegionCode] [varchar](10)'$.data.RegionCode'
[DueDate] [datetime2](7)'$.data.DueDate',
[SchedulStartDate] [datetime2](7)'$.data.SchedulStartDate',
)
)
MERGE [warm].[table] AS TARGET
USING JsonToTable AS SOURCE
ON (TARGET.ID = SOURCE.ID)
WHEN MATCHED THEN
UPDATE SET
TARGET.[RegionCode] = (SOURCE.[RegionCode]
TARGET.[DueDate] = [dbo].[ufn_cast_string_to_date](SOURCE.[DueDate])
,TARGET.[SchedulStartDate] = [dbo].[ufn_cast_string_to_date](SOURCE.[SchedulStartDate])
WHEN NOT MATCHED THEN
INSERT
(
[SourceID]
,[ID]
,[RegionCode]
,[DueDate]
,[SchedulStartDate])
VALUES
(
1
,[ID]
,[RegionCode]
,[dbo].[ufn_cast_string_to_date](SOURCE.[DueDate])
,[dbo].[ufn_cast_string_to_date](SOURCE.[SchedulStartDate])
);
END
END TRY
END
I Want to execute it with the request below :
DECLARE #return_value int
EXEC #return_value = [warm].[usp_upsert_warm_table]
#Json = N'{
"type" : "table",
"source" : "informations",
"time" : "2018-04-05T17:31:00Z",
"id" : "A11-111-111",
"data" : {"
"ID":"123-56",
"RegionCode":"2",
"DueDate":"2020-13-14T10:54:00",
"SchedulStartDate":"2020-12-14T10:54:00"
}'}
I get this Message Error :
JSON text is not properly formatted. Unexpected character '.' is found at position 480.**
This is the Valid input :
DECLARE #return_value int
EXEC #return_value = [warm].[usp_upsert_warm_table]
#Json = N'
{
"type" : "table1",
"source" : "",
"id" : "A111-111-11",
"time" : "2020-12-14 10:54:00",
"data" :{
"ApplicationID":"INFORMATIONS",
"ID":"157faf1657c-100",
"RegionCode":"2",
"DueDate":"2020-12-14 10:54:00",
"SchedulStartDate":"2020-12-14 10:54:00"}'}
For my input date : 2020-12-14 10:54:00 i deleteed the T in the middle
for my S.P : I change the type of My variables from datetime To varchar :
CREATE PROCEDURE [warm].[usp_upsert_warm_table]
...
[ID] [varchar](50) '$.data.ID',
[RegionCode] [varchar](10)'$.data.RegionCode'
[DueDate] [varchar](40)'$.data.DueDate',
[SchedulStartDate] [varchar](10)'$.data.SchedulStartDate',
....
thanks in advance. Here i want to send a array of objects to the stored procedure via mssql connection to the ms sql-server from NodeJs backend. i have submitted my Stored Procedure and Backend code block.
--- Stored Procedure ---
CREATE PROCEDURE [dbo].[AddProductVariant]
#ProductId BIGINT ,
#Name NVARCHAR(200) ,
#InputTypeId TINYINT ,
#Attributes dbo.UT_ProductVariant READONLY
AS
BEGIN
BEGIN TRY
SET NOCOUNT ON;
DECLARE #Id BIGINT
INSERT INTO dbo.ProductVariants
( ProductId, Name, InputTypeId )
VALUES ( #ProductId -- ProductId - bigint
, #Name -- Name - nvarchar(50)
, #InputTypeId -- InputTypeId - tinyint
)
SET #Id = SCOPE_IDENTITY()
EXECUTE MergeProductVariantAttributes #Id, #Attributes
SELECT *
FROM SellEasyDb.dbo.ProductVariants
WHERE Id = #Id
--SELECT * FROM SellEasyDb.dbo.UserGroups WHERE SellEasyDb.dbo.UserGroups.Id = #Id
RETURN 0
END TRY
BEGIN CATCH
RETURN ##ERROR
END CATCH
END
--- NODE TS CODE ---
const pool = dbConnect.connect();
const request = dbConnect.request();
request.input("ProductId", req.body.productId);
request.input("Name", req.body.name);
request.input("InputTypeId", req.body.inputTypeId);
request.input("Attributes", req.body.attributes); // this is the array i want to send to SP
await request.execute("AddProductVariant", async (err: any, result: any, resultvalue: any) => {
debugger;
}
});
--- ERROR ---
class:16
code:'EREQUEST'
lineNumber:0
message:'Operand type clash: nvarchar is incompatible with UT_ProductVariant'
name:'RequestError'
number:206
state:2
--- User Define Type ---
CREATE TYPE UT_ProductVariant AS TABLE
(
[Id] [BIGINT],
[Title] [VARCHAR](200) NOT NULL,
[PriceAdjustment] [DECIMAL](18, 2) NOT NULL,
[IsDefault] [BIT] NOT NULL,
[SortOrder] [INT] NOT NULL,
[VarientId] [BIGINT],
[ProductId] [BIGINT]
)
Our middleware software receives an XML document and forwards it to another software. However, there is one field in the target software (ext_text_10), that I do NOT want to overwrite.
Upon receiving the XML, I would like to call a stored proc, that should query the target database table to find the current ext_text_10 value, and insert a new element in the incoming XML with the resulting value, and then pass it on. This way we will simply pass the current value for that field.
The procedure below is reading the XML, building it again by preserving everything from it, and then inserting one element.
However, it does not return any result. Below is my procedure, and my source XML.
I hope somebody can tell me what is wrong. This is SQL Server 2016.
CREATE PROCEDURE [dbo].[z_ION_GetCurrentCostCenterData] (#xmlData xml)
AS
BEGIN
-- Prevent extra result sets from interfering with SELECT statements
SET NOCOUNT ON;
-- Parse XML
DECLARE #parsedXmlData int;
EXEC sp_xml_preparedocument #parsedXmlData OUTPUT, #xmlData;
DECLARE
#tenantID varchar(50),
#acc_entity varchar(3),
#doc_id varchar(50),
#anl_code varchar(15),
#anl_dim_id varchar(2),
#lookup_code varchar(15),
#anl_code_name varchar(50),
#prohibit_posting varchar(1),
#statusCode varchar(1),
#anl_cat_id varchar(15),
#ext_text_6 varchar(50),
#ext_text_7 varchar(50),
#ext_text_8 varchar(50),
#ext_text_9 varchar(50),
#ext_num_1 varchar(50),
#ext_num_2 varchar(50),
#ext_num_3 varchar(50),
#ext_num_4 varchar(50),
#ext_num_5 varchar(50),
#ext_date_1 varchar(50),
#ext_date_2 varchar(50),
#ext_fixed_1 varchar(50),
#ext_fixed_2 varchar(50),
#ext_fixed_3 varchar(50),
#TableName NVarchar(255)
--Get data from XML
select
#tenantID = tenantID,
#acc_entity = acc_entity,
#doc_id = doc_id,
#anl_code = anl_code,
#anl_dim_id = anl_dim_id,
#lookup_code = lookup_code,
#anl_code_name = anl_code_name,
#prohibit_posting = prohibit_posting,
#statusCode = statusCode,
#anl_cat_id = anl_cat_id,
#ext_text_6 = ext_text_6,
#ext_text_7 = ext_text_7,
#ext_text_8 = ext_text_8,
#ext_text_9 = ext_text_9,
#ext_num_1 = ext_num_1,
#ext_num_2 = ext_num_2,
#ext_num_3 = ext_num_3,
#ext_num_4 = ext_num_4,
#ext_num_5 = ext_num_5,
#ext_date_1 = ext_date_1,
#ext_date_2 = ext_date_2,
#ext_fixed_1 = ext_fixed_1,
#ext_fixed_2 = ext_fixed_2,
#ext_fixed_3 = ext_fixed_3
from OPENXML (#parsedXmlData,'DataArea',2)
with
(tenantID varchar(50) 'Sync/TenantID',
acc_entity varchar(3) 'Sync/AccountingEntityID',
doc_id varchar(50) 'SunSystemsAnalysisCodes/DocumentID/ID',
anl_code varchar(15) 'SunSystemsAnalysisCodes/AnalysisCode',
anl_dim_id varchar(2) 'SunSystemsAnalysisCodes/AnalysisDimensionId',
lookup_code varchar(15) 'SunSystemsAnalysisCodes/LookupCode',
anl_code_name varchar(50) 'SunSystemsAnalysisCodes/Name',
prohibit_posting varchar(1) 'SunSystemsAnalysisCodes/ProhibitPosting',
statusCode varchar(1) 'SunSystemsAnalysisCodes/Status',
anl_cat_id varchar(15) 'SunSystemsAnalysisCodes/AnalysisCatID/AnlCat_SHead',
ext_text_6 varchar(50) 'SunSystemsAnalysisCodes/ExtendedAnalysis/ExtensionText6',
ext_text_7 varchar(50) 'SunSystemsAnalysisCodes/ExtendedAnalysis/ExtensionText7',
ext_text_8 varchar(50) 'SunSystemsAnalysisCodes/ExtendedAnalysis/ExtensionText8',
ext_text_9 varchar(50) 'SunSystemsAnalysisCodes/ExtendedAnalysis/ExtensionText9',
ext_num_1 varchar(50) 'SunSystemsAnalysisCodes/ExtendedAnalysis/ExtensionNumber1',
ext_num_2 varchar(50) 'SunSystemsAnalysisCodes/ExtendedAnalysis/ExtensionNumber2',
ext_num_3 varchar(50) 'SunSystemsAnalysisCodes/ExtendedAnalysis/ExtensionNumber3',
ext_num_4 varchar(50) 'SunSystemsAnalysisCodes/ExtendedAnalysis/ExtensionNumber4',
ext_num_5 varchar(50) 'SunSystemsAnalysisCodes/ExtendedAnalysis/ExtensionNumber5',
ext_date_1 varchar(50) 'SunSystemsAnalysisCodes/ExtendedAnalysis/ExtensionDate1',
ext_date_2 varchar(50) 'SunSystemsAnalysisCodes/ExtendedAnalysis/ExtensionDate2',
ext_fixed_1 varchar(50) 'SunSystemsAnalysisCodes/ExtendedAnalysis/ExtensionFixed1',
ext_fixed_2 varchar(50) 'SunSystemsAnalysisCodes/ExtendedAnalysis/ExtensionFixed2',
ext_fixed_3 varchar(50) 'SunSystemsAnalysisCodes/ExtendedAnalysis/ExtensionFixed3'
);
--Create XML to return
select
[EXT_TEXT_10] as 'SunSystemsAnalysisCodes/ExtendedAnalysis/ExtensionText10'
from [dbo].[IMT_ANL_CODE_EXT]
where [ANL_CAT_ID] = #anl_cat_id and [ANL_CODE] = #anl_code
for XML PATH ('SunSystemsAnalysisCodes'), root('DataArea')
EXEC sp_xml_removedocument #parsedXmlData
END
Source XML:
<DataArea xmlns:my="http://schema.infor.com/InforOAGIS/2">
<Sync>
<TenantID>INFRA_TRN</TenantID>
<AccountingEntityID>IMT</AccountingEntityID>
<ActionCriteria>
<ActionExpression actionCode="Change" />
</ActionCriteria>
</Sync>
<SunSystemsAnalysisCodes>
<DocumentID>
<ID variationID="1495808583000">PRO 00002</ID>
</DocumentID>
<IONStatus>
<Code listID="GenericStatus">Open</Code>
</IONStatus>
<AnalysisCode>PRO17</AnalysisCode>
<AnalysisDimensionId>01</AnalysisDimensionId>
<LookupCode>Informatiesyste</LookupCode>
<Name>Informatiesysteem Relatics 10</Name>
<ProhibitPosting>0</ProhibitPosting>
<Status>0</Status>
<AnalysisCatID>
<AnlCat_SHead>COST CENTRE</AnlCat_SHead>
</AnalysisCatID>
<ExtendedAnalysis>
<ExtensionText6>SVE</ExtensionText6>
<ExtensionText7>Open</ExtensionText7>
<ExtensionText8 />
<ExtensionNumber1>81700</ExtensionNumber1>
<ExtensionNumber2 />
<ExtensionNumber3 />
<ExtensionNumber4 />
<ExtensionNumber5 />
<ExtensionDate1>01012016</ExtensionDate1>
<ExtensionDate2>31122016</ExtensionDate2>
<ExtensionFixed1>1</ExtensionFixed1>
<ExtensionFixed2>2</ExtensionFixed2>
<ExtensionFixed3>2</ExtensionFixed3>
</ExtendedAnalysis>
</SunSystemsAnalysisCodes>
</DataArea>
If this doesn't help you, please answer the questions from my comment below your question!
My magic crystall ball tells me, that you might be looking for something like this (shortened for brevity):
DECLARE #xml XML=
N'<DataArea xmlns:my="http://schema.infor.com/InforOAGIS/2">
<Sync>
<TenantID>INFRA_TRN</TenantID>
<!-- more elements -->
</Sync>
<SunSystemsAnalysisCodes>
<DocumentID>
<ID variationID="1495808583000">PRO 00002</ID>
</DocumentID>
<!-- more elements -->
<ExtendedAnalysis>
<ExtensionText6>SVE</ExtensionText6>
<ExtensionText7>Open</ExtensionText7>
<ExtensionText8 />
<ExtensionNumber1>81700</ExtensionNumber1>
<ExtensionNumber2 />
<ExtensionNumber3 />
<ExtensionNumber4 />
<ExtensionNumber5 />
<ExtensionDate1>01012016</ExtensionDate1>
<ExtensionDate2>31122016</ExtensionDate2>
<ExtensionFixed1>1</ExtensionFixed1>
<ExtensionFixed2>2</ExtensionFixed2>
<ExtensionFixed3>2</ExtensionFixed3>
</ExtendedAnalysis>
</SunSystemsAnalysisCodes>
</DataArea>';
--This is the content you want to introduce
DECLARE #ContentToAdd NVARCHAR(MAX)=N'SunSystemsAnalysisCodes/ExtendedAnalysis/ExtensionText10';
--This XML_DML-statement will insert your content with the given name before the <ExtensionNumber1> (which must exist! Other positions are possible of course)
SET #xml.modify(N'insert <ExtensionText10>{sql:variable("#ContentToAdd")}</ExtensionText10>
before (/DataArea/SunSystemsAnalysisCodes/ExtendedAnalysis/ExtensionNumber1)[1]');
--Check the output:
SELECT #xml;
<DataArea xmlns:my="http://schema.infor.com/InforOAGIS/2">
<Sync>
<TenantID>INFRA_TRN</TenantID>
<!-- more elements -->
</Sync>
<SunSystemsAnalysisCodes>
<DocumentID>
<ID variationID="1495808583000">PRO 00002</ID>
</DocumentID>
<!-- more elements -->
<ExtendedAnalysis>
<ExtensionText6>SVE</ExtensionText6>
<ExtensionText7>Open</ExtensionText7>
<ExtensionText8 />
<ExtensionText10>SunSystemsAnalysisCodes/ExtendedAnalysis/ExtensionText10</ExtensionText10>
<ExtensionNumber1>81700</ExtensionNumber1>
<ExtensionNumber2 />
<ExtensionNumber3 />
<ExtensionNumber4 />
<ExtensionNumber5 />
<ExtensionDate1>01012016</ExtensionDate1>
<ExtensionDate2>31122016</ExtensionDate2>
<ExtensionFixed1>1</ExtensionFixed1>
<ExtensionFixed2>2</ExtensionFixed2>
<ExtensionFixed3>2</ExtensionFixed3>
</ExtendedAnalysis>
</SunSystemsAnalysisCodes>
</DataArea>
Let's define:
create table cities
(
ID int identity,
name varchar(50) unique
)
create function getID (#name varchar(50)) returns int
begin
declare #id int
select #id=ID from cities where name=#name
return #id
end
create procedure addLine
#cityID int
as begin
...
end
Is it possible to execute a procedure with value returned by function, as follows?
exec addLine getID('Warsaw')
exec addLine dbo.getID('Warsaw')
exec addLine (select dbo.getID('Warsaw'))
I tried above and it did not help.
Microsoft says that this is not possible. You can not pass result of a function to procedure as a parameter:
[ { EXEC | EXECUTE } ]
{
...
[ [ #parameter = ] { value
| #variable [ OUTPUT ]
| [ DEFAULT ]
}
]
...
}
[;]
So, only constant values, variables and DEFAULT keyword are permitted.
2 possible ways of doing this are:
1: declare variable
declare #i int = dbo.getID('Warsaw')
exec addLine #i
2: use dynamic query
DECLARE #cmd NVARCHAR(MAX) = 'exec addLine ' + CAST(dbo.getID('Warsaw') AS NVARCHAR(MAX))
EXEC(#cmd)
This will "execute a procedure with value returned by function"
It just won't do it 'inline'
declare #id int
select #id = dbo.getID('Warsaw')
exec addLine #id
I have a stored procedure where I need to run three separate SELECT statements and store the result in a variable.
I tried something like this:
SELECT #tier1MenuIds = Id
FROM TheGateKeeper.NavigationTier1
WHERE ([Page Name] = #currentSlug)
SELECT #tier2MenuIds = Id
FROM TheGateKeeper.NavigationTier2
WHERE ([Page Name] = #currentSlug)
SELECT #tier3MenuIds = Id
FROM TheGateKeeper.NavigationTier3
WHERE ([Page Name] = #currentSlug)
But it gives me an error saying
Incorrect syntax near '('.
The statement works if I remove the bottom two SELECTs. Any other options?
Edit: I am using SQL Server. Here is the full code:
CREATE PROCEDURE [TheGateKeeper].[editContent]
#description nvarchar(300),
#content nvarchar(MAX),
#title nvarchar(50),
#dateModified date,
#headerImageName nvarchar(100),
#slug nvarchar(50),
#id int
AS
BEGIN
SET NOCOUNT ON;
DECLARE #currentSlug as nvarchar(100);
DECLARE #tier1MenuIds as int;
DECLARE #tier2MenuIds as int;
DECLARE #tier3MenuIds as int;
/* Check if the post exists */
SELECT #currentSlug = Slug
FROM TheGateKeeper.Posts
WHERE (Id = #id)
IF (##ROWCOUNT = 1)
BEGIN
/* Temporarily unlink all menu items linking to post */
SELECT #tier1MenuIds = Id
FROM TheGateKeeper.NavigationTier1
WHERE ([Page Name] = #currentSlug)
SELECT #tier2MenuIds = Id
FROM TheGateKeeper.NavigationTier2
WHERE ([Page Name] = #currentSlug)
SELECT #tier3MenuIds = Id
FROM TheGateKeeper.NavigationTier3
WHERE ([Page Name] = #currentSlug)
/* Update the post in the database */
UPDATE Posts
SET (Description = #description, [Content] = #content, Title = #title, [Date Modified] =#dateModified, HeaderImageName = #headerImageName, slug =#slug)
WHERE id = #id
RETURN 1
END
ELSE
BEGIN
RETURN 0
END
Remove the parentheses from your UPDATE statement; they are unnecessary.
Your update statement should be:
UPDATE Posts
SET Description = #description, [Content] = #content, Title = #title,
[Date Modified] =#dateModified, HeaderImageName = #headerImageName,
slug =#slug
WHERE id = #id