I creating a function and I have a red error line under the BEGIN keyword and I can't figure out what is wrong with this query?
USE PR
GO
CREATE FUNCTION fnInsCosts
(#NoDependents int)
RETURNS TABLE
BEGIN
RETURN
(SELECT
EmpName,
SUM(BaseCost) AS TotBaseCost,
SUM(SpouseIns) AS TotSpouseCost,
SUM(DepIns) AS TotDepCost,
SUM(DentalCost) AS TotDentalCost,
SUM(SUM(BaseCost) + SUM(SpouseIns) + SUM(DepIns) + SUM(DentalCost)) AS TotalInsCost
FROM
vwPayroll
WHERE
Dependants = #NoDependents
GROUP BY
EmpName)
END;
try
CREATE FUNCTION dbo.fnInsCosts
(#NoDependents int)
RETURNS TABLE
AS
RETURN (
SELECT EmpName, SUM(BaseCost) AS TotBaseCost, SUM(SpouseIns) AS TotSpouseCost
, SUM(DepIns) AS TotDepCost, SUM(DentalCost) AS TotDentalCost
, SUM(SUM(BaseCost) + SUM(SpouseIns) + SUM(DepIns) + SUM(DentalCost)) AS TotalInsCost
FROM vwPayroll
WHERE Dependants = #NoDependents
GROUP BY EmpName
)
Related
ParseValuesJson and insertToTable are user defined function.
The following is the result of the execution ( ParseValuesJson ) :
declare
#json nvarchar(max)=N'{
"Book":{
"IssueDate":"02-15-2019"
, "Detail":{
"Type":"Any Type"
, "Author":{
"Name":"Annie"
, "Sex":"Female"
}
}
, "Chapter":[
{
"Section":"1.1"
, "Title":"Hello world."
}
,
{
"Section":"1.2"
, "Title":"Be happy."
}
]
, "Sponsor":["A","B","C"]
}
}'
declare
#tempTable table (
topKey nvarchar(4000)
, [key] nvarchar(4000)
, IsType bit
, IsList bit
, [value] nvarchar(4000))
--execute
insert #tempTable
select * from GetValuesJson(#json,default)
topKey Key isType isList Value
--
Book Type 0 0 Any Type
Book Author 1 0 {"Name":"Annie", "Sex":"Female"}
Book IssueDate 0 0 02-15-2019
Book Chapter 1 1 [{"Section":"1.1", "Title":"Hello world."}, {"Section":"1.2", "Title":"Be happy."}]
Book Sponsor 1 1 ["A","B","C"]
As title, If ignore what the function doing, how can I achieve the following purpose?
If IsType=1 , I want to call function ParseValuesJson;
If IsType=0 , I want to call function insertToTable.
But I found that sql case can not use like that.
This sql query may execute recursively and call different functions accordingly at the same level.
It means that I can't parse all string (ParseValuesJson) first and then insert the result (insertToTable) to the table.
Is there any other way to achieve?
select
case IsType when 1 then
ParseValuesJson('{"' + [key] + '":' + [value] + '}',IsList)
else
insertToTable(topKey,[key])
end
from ParseValuesJson(#json,default)
Well, the easiest thing to do is to split it into two separate SELECTs.
select ParseValuesJson('{"' + [key] + '":' + [value] + '}',IsList)
from ParseValuesJson(#json,default)
where IsType = 1
select insertToTable(topKey,[key])
from ParseValuesJson(#json,default)
where IsType = 0
But I guess this approach won't help you since inside user defined functions you cannot use INSERT, UPDATE, DELETE statements -> i.e modify table data
So I guess that to parse the JSON you'd need to user recursive CTE to parse all values first and then to insert them into temp table at once.
Something like this:
;WITH ParsedJSON(topKey, [key], IsType, IsList, [value])
AS
(
SELECT topKey, [key], IsType, IsList, [value]
FROM ParseValuesJson('{"' + [key] + '":' + [value] + '}',IsList)
UNION ALL
SELECT topKey, [key], IsType, IsList, [value]
FROM ParsedJSON
WHERE IsType = 1
)
insert #tempTable
select * from ParsedJSON
I got one problem while insert data from one db to another
below is my code:
INSERT
INTO myarchivedb.dbo.tblStoreOrderArchive
(
[StoreOrderId]
,[CompanyId]
,[SiteId]
)
SELECT StoreOrderId
,CompanyId
,SiteId
FROM mycurrentdb.dbo.tblStoreOrder
Above code is working fine but myarchivedb and mycurrentdb will change periodically. how to do it dynamically using a variable.
you can try like this
declare #db1 nvarchar(99) = 'myarchivedb.dbo.tblStoreOrderArchive';
declare #db2 nvarchar(99) = 'mycurrentdb.dbo.tblStoreOrder';
-- make sure your query and syntax is correct
PRINT ('INSERT INTO ' + #db1 +
'([StoreOrderId] ,[CompanyId] ,[SiteId] ) SELECT StoreOrderId ,CompanyId ,SiteId FROM ' + #db1)
EXEC ('INSERT INTO ' + #db1 +
'([StoreOrderId] ,[CompanyId] ,[SiteId] ) SELECT StoreOrderId ,CompanyId ,SiteId FROM ' + #db1)
I have a procedure like this;
SET #Oldname = (SELECT name
FROM [Marketing].[dbo].[_Users]
WHERE ID = #MID);
Everything is okay but some members got xxx, xxx_A1,xxx_A2,xxx_A3, while selecting these members I want to select without _A1 , _A2 , A_30
How can I select it?
Try reversing string, find first index of _ and apply substring:
DECLARE #s NVARCHAR(MAX) = 'John_Smith_234'
DECLARE #t TABLE ( Name NVARCHAR(50) )
INSERT INTO #t
VALUES ( 'John_Smith_234' ),
( 'Michael_Jordan' ),
( 'Honore_De_Balzak_234' )
SELECT SUBSTRING(Name, 1, LEN(Name) - CHARINDEX('_', REVERSE(Name))) AS Name
FROM #t
Output:
Name
John_Smith
Michael
Honore_De_Balzak
try this
select left(name, len(name)-charindex('_', reverse(name))) name
from whatever
Assure that you add a '%' sign to your #MID Variable, looking like 'xxx%'
Than SELECT with LIKE instead of = :
SET #Oldname = (SELECT name From [Marketing].[dbo].[_Users] Where ID LIKE #MID);
I think you may also add the '%' sign in qour query (haven't tried):
SET #Oldname = (SELECT name From [Marketing].[dbo].[_Users] Where ID LIKE #MID+'%');
My query is for convert varchar into string,
select top(5)'Insert into jobs(minexperience,maxexperience)values('+
cast(substring(Experience as varchar(50)),0,patindex('%to%',Experience))*365*24*60*60,
cast(substring(Experience as
varchar(50)),patindex('%to%',Experience)+2,patindex('%Years%',Experience)-patindex('%to%',Experience)-2)*365*24*60*60+')'
from requirementsdetailsfororganization
In my below query i have an error "Incorrect syntax near the keyword 'AS'."
I want to convert string to integer.
Any Help?
Possible this helpful for you -
SELECT TOP(5) 'INSERT INTO dbo.jobs(minexperience,maxexperience) VALUES(' +
CAST(SUBSTRING(
CAST(r.Experience AS VARCHAR(50))
, 0
, r.ToExperience) * 31536000
AS VARCHAR(50))
+ ',' +
CAST(SUBSTRING(
CAST(r.Experience AS VARCHAR(50))
, r.ToExperience + 2
, patindex('%Years%', r.Experience) - r.ToExperience - 2) * 31536000
AS VARCHAR(50))
+')'
FROM (
SELECT
r.Experience
, ToExperience = PATINDEX('%to%', r.Experience)
FROM dbo.requirementsdetailsfororganization r
) r
I my project i have a session variable that variable contains list of recently accessed values.With help of these values i need to get data from database.For this i wrote a storedprocedure with single parameter(#myparam) but its giving only one row from table.
How can get list of rows from table using session list for storedprocedure?
If i understood you right, try this
CREATE function [dbo].[csv2tbl](#list nvarchar(max), #delimiter nvarchar(10))
returns #res table ([index] int PRIMARY KEY, col nvarchar(max))
AS BEGIN
with tbl_for_csv as
(
select 0 as [index] ,left(#list + #delimiter+#delimiter,charindex(#delimiter,#list + #delimiter+#delimiter) -1)as col,
right(#list + #delimiter+#delimiter,len(#list + #delimiter+#delimiter) - charindex(#delimiter,#list + #delimiter+#delimiter)) as Str
union all
select [index]+1, left(Str,charindex(#delimiter,Str) - 1)as Col,
right(Str,len(Str) - charindex(#delimiter,Str)) from tbl_for_csv
where len(right(Str,len(Str) - charindex(#delimiter,Str))) > 0
)
INSERT #res
select [index], col from tbl_for_csv option (MAXRECURSION 0);
return;
END
GO
SELECT *
from YourTable
JOIN [dbo].[csv2tbl](#recentAssetList, ',') x ON x.col = yourtable.Id