Incorrect syntax near the keyword 'DECLARE' - cpu

I have query to calcuate CPU usage and need to copy the output to table but getting the error
Incorrect syntax near the keyword 'DECLARE'.
Please find the query.
Insert into dbo.cpudata([database],[system cpu],[database cpu],[%],[Date&time])
DECLARE #total INT
SELECT #total=sum(cpu) FROM sys.sysprocesses sp (NOLOCK)
join sys.sysdatabases sb (NOLOCK) ON sp.dbid = sb.dbid
SELECT sb.name 'database', #total 'system cpu', SUM(cpu) 'database cpu', CONVERT(DECIMAL(4,1), CONVERT(DECIMAL(17,2),SUM(cpu)) / CONVERT(DECIMAL(17,2),#total)*100) '%', GETDATE () as [Date&time]
FROM sys.sysprocesses sp (NOLOCK)
JOIN sys.sysdatabases sb (NOLOCK) ON sp.dbid = sb.dbid
--WHERE sp.status = 'runnable'
GROUP BY sb.name
ORDER BY CONVERT(DECIMAL(4,1), CONVERT(DECIMAL(17,2),SUM(cpu)) / CONVERT(DECIMAL(17,2),#total)*100) desc

Could you move to statement which populates #total above the insert.
DECLARE #total INT
SELECT #total=sum(cpu) FROM sys.sysprocesses sp (NOLOCK)
join sys.sysdatabases sb (NOLOCK) ON sp.dbid = sb.dbid
Insert into dbo.cpudata([database],[system cpu],[database cpu],[%],[Date&time])
...............

You can't DECLARE a variable in the middle of an INSERT statement. You've done so, between the INSERT INTO <columnlist> and SELECT <columnlist>.
Move the declaration above the start of the INSERT instead.

Related

why SSRS asking to Define query parameters when already defined?

I have the below query which is working well in SQL. But when I use this query in ssrs(Visual studio 2015) it is giving me error saying define query parameters. I have already defined values for parametes but still getting the error. I feel something from the SQL query which s not getting supported in SSRS. Can anyone help?
[![SET FMTONLY OFF
USE GODSDB
declare
#start date = getdate() - 100
, #end date = getdate()
drop table #CallLog
declare #code varchar(max), #TableName varchar(max), #SeverName varchar(max)
--IF object_id('tempdb..#CallLog') IS NOT NULL DROP TABLE #CallLog
CREATE TABLE #CallLog (
\[JurisdictionShortIdentifier\] VARCHAR(100),
\[ContractCallLogOID\] INT,
\[ContractCallLogProcessQueueOID\] INT,
\[ContractOID\] INT,
\[CallDate\] DATETIME,
\[CallHandledBy\] VARCHAR(60),
\[CallLogOldGreenUnit\] INT,
\[CallLogNewGreenUnit\] INT,
\[Comment\] VARCHAR(7500)
)
set #TableName = '#CallLog'
set #SeverName = 'BA_GBASSTOCSISDB' -- sp_linkedservers
set #code = '
;with XMLNAMESPACES(DEFAULT ''http://tempuri.org/GEOUnit.xsd'')
select
ccl.JurisdictionShortIdentifier,
ccl.ContractCallLogOID,
que.ContractCallLogProcessQueueOID,
ccl.ContractOID,
ccl.db_insertDate as CallDate,
ccl.db_insertBy as CallHandledBy,
convert(xml, que.XMLString).value(''(/GEOUnit/GreenPowerUnits/GreenPowerUnitsOld)\[1\]'',''int'') as CallLogOldGreenUnit,
convert(xml, que.XMLString).value(''(/GEOUnit/GreenPowerUnits/GreenPowerUnitsNew)\[1\]'',''int'') as CallLogNewGreenUnit,
cmt.Comment
from CSISDB.dbo.ContractCallLog as ccl (nolock)
left join CSISDB.dbo.ContractCallLogProcessQueue as que (nolock) on ccl.ContractCallLogOID = que.ContractCallLogOID
left join CSISDB.dbo.Comment as cmt (nolock) on ccl.ContractCallLogOID = cmt.FKObjectOID and cmt.FKTableObjectOID = 1008
where 1 = 1
and ccl.ContractCallLogStatusIdentifier in (''GMOD'', ''GUS'', ''GI'')
and ccl.ContractCallLogReasonIdentifier in (''Changed'', ''GEOR'', ''NULL'', ''GEO'', ''GEO0'', ''GEO1'', ''GEO3'', ''GEO2'', ''CDR'', ''GEO4'', ''GEO5'', ''JUST GREEN adder'', ''JustGreen'')
--and ccl.JurisdictionShortIdentifier = ''AG''
and ccl.SourceSystemIdentifier = ''GBASS''
and ccl.db_insertDate between #start and #end
--and ccl.ContractCallLogOID = 57131879 --> TEST CASE
'
set #code = replace(#code, '#start', '''' + convert(varchar, convert(date, #start, 101)) + '''')
set #code = replace(#code, '#end', '''' + convert(varchar, convert(date, dateadd(day, 1, #end), 101)) + '''')
set #code = concat('insert into ', #TableName, ' select * from openquery (', #SeverName, ', ''' , replace(#code, '''', '''''') , ''')')
print #code
exec(#code)
-- select * from #CallLog where ContractCallLogOID = 57707501
-- some call log have multiple process queues, delete the process queues that don't is not modifying the geo units
delete a
from #CallLog as a
inner join #CallLog as b on a.ContractCallLogOID = b.ContractCallLogOID
and a.ContractCallLogProcessQueueOID != b.ContractCallLogProcessQueueOID
and a.CallLogNewGreenUnit is null
and b.CallLogNewGreenUnit is not null
--select * from #CallLog
select
ccl.JurisdictionShortIdentifier,
ccl.ContractCallLogOID,
ccl.ContractCallLogProcessQueueOID,
cnt.RtlrContractIdentifier,
ccl.ContractOID,
cst.ContractStatusIdentifier as ContractStatus,
ccl.CallLogOldGreenUnit,
ccl.CallLogNewGreenUnit,
cur.GreenLevelIndicator as CurrentGreenUnit,
cur.db_insertDate as GreenUnitLastUpdateDate,
cur.db_insertBy as GreenUnitLastUpdateBy,
ccl.CallDate,
ccl.CallHandledBy,
ccl.Comment
from #CallLog as ccl
inner join Contract as cnt (nolock) on ccl.ContractOID = cnt.ContractOID
and ccl.CallLogOldGreenUnit != ccl.CallLogNewGreenUnit
inner join ContractState as cst (nolock) on cnt.ContractOID = cst.ContractOID
left join ContractGreenContent as cur (nolock) on cnt.ContractOID = cur.ContractOID
and isnull(cur.EffectiveEndDate, dateadd(day, 1, getdate())) >= getdate()
left join ContractGreenContent as his (nolock) on cnt.ContractOID = his.ContractOID
and ccl.CallLogNewGreenUnit = his.GreenLevelIndicator
and his.db_insertDate between dateadd(day, -1, ccl.CallDate) and dateadd(day, 1, ccl.CallDate)
where his.ContractGreenContentOID is null
--select * from #CallLog
union all
select
ccl.JurisdictionShortIdentifier,
ccl.ContractCallLogOID,
ccl.ContractCallLogProcessQueueOID,
cnt.RtlrContractIdentifier,
ccl.ContractOID,
cst.ContractStatusIdentifier as ContractStatus,
ccl.CallLogOldGreenUnit,
ccl.CallLogNewGreenUnit,
cur.GreenLevelIndicator as CurrentGreenUnit,
cur.db_insertDate as GreenUnitLastUpdateDate,
cur.db_insertBy as GreenUnitLastUpdateBy,
ccl.CallDate,
ccl.CallHandledBy,
ccl.Comment
from #CallLog as ccl
inner join Contract as cnt (nolock) on ccl.ContractOID = cnt.ContractOID
and isnull(ccl.CallLogOldGreenUnit, 0) = isnull(ccl.CallLogNewGreenUnit, 0)
inner join ContractState as cst (nolock) on cnt.ContractOID = cst.ContractOID
left join ContractGreenContent as cur (nolock) on cnt.ContractOID = cur.ContractOID
and isnull(cur.EffectiveEndDate, dateadd(day, 1, getdate())) >= getdate()
SET FMTONLY ON][1]][1]
Make sure your parameter names and SQL variables are all spelled exactly the same, they are case sensitive.
Also try declaring each variable on it own line with its own DECLARE statement. I've seen this fix this issue 'sometimes'
Your parameters are inside your #SQL query variable. The server that you are running the OPENQUERY from doesn't recognize the parameters since they were declared on another server.
Put the parameter declarations inside your SQL variable:
set #code = '
declare
#start date = getdate() - 100
, #end date = getdate()
...

Ordering columns by Primary Key position in PostgreSQL

I am new to PostgreSQL and was wondering if there is a table which matches Oracle's user_cons_columns table which provides a column position column similar to user_cons_columns.position. Essentially, I am trying to convert the following oracle code to PostgreSQL. It attains the PK columns in order of PK definition:
Oracle Code (Original):
select a.table_name tab_name,
a.colum_name col_name,
a.position col_order
from user_cons_columns a,
user_constraints b
where a.table_name = b.table_name
and a.constraint_name = b.constraint_name
and b.constraint_type = 'P'
and a.table_name = 'some_table_name';
PostgreSQL Code (Oracle Equiv):
/* Below is my attempt at the PostgreSQL conversion */
select isc.table_name tab_name,
isc.column_name col_name,
isc.ordinal_position col_order
from pg_attribute as pga
inner join pg_class as pgc on pga.attrelid = pgc.oid
inner join pg_namespace as pgn on pgn.oid = pgc.relnamespace
inner join information_schema.columns as isc on isc.column_name = pga.attname
and isc.table_name = pgc.relname
where isc.table_name = 'sometablename';
In my PostgreSQL conversion attempt I am missing the relationship between the constraint and its position but use the column position. Which is not the same. Is there a way to do the former? Thanks in advance!
The column numbers of a constraint and their order are stored in pg_constraint.conkey; for foreign keys, the corresponding numbers of the target columns are in pg_constraint.confkey.
The description of table columns is in pg_attribute; the column number is stored in attnum.
Below is the solution that I derived thanks to the answer from #Laurenz Albe.
select isc.table_name tab_name,
isc.col_name col_name,
pgco.conkey[1] col_order
from pg_attribute as pga
inner join pg_class as pgc on pga.attrelid = pgc.oid
inner join pg_namespace as pgn on pgn.oid = pgc.relnamespace
inner join information_schema.columns as isc on isc.column = pga.attname
and isc.table_name = pgc.relname
inner join pg_constraint as pgco on pgco.conkey[1] = pga.attnum
and pgco.connamespace = pgc.relnamespace
and pgco.conrelid = pga.attrelid
where isc.table_name = 'sometablename'
and pgco.contype ='p';
Hope this is useful to someone else.

Oracle subquery does not see the variable on second level

It returns
"invalid identifier" on "pe.partyid" (level 2).
Can you please advise on how to correct?
update table_x pe
set pe.taxidnumber =
(select tin
from (select tin
,version
,max(version) over(partition by partyid) maxversion
from table_y
where partyid = pe.partyid)
where version = maxversion);
In Oracle you can use a table alias in an immediate subquery (one level down), but not in more deeply-nested subqueries.
You can go around this with factored subqueries (WITH clause). But in your case, it's not clear why you need a correlated sub-subquery. Move the WHERE condition on matching by partyid to the middle query; that way the inner-most query will be uncorrelated, so it will be computed just once. Move the partyid check next to version = maxversion.
I would do:
create global temporary table tempt as select tin, partyid from table_y where rownum < 2;
insert into tempt select tin, partyid
from (select tin
,partyid
,version
,max(version) over(partition by partyid) maxversion
from table_y
where version = maxversion);
merge into table_x t
using tempt d
on (t.partyid = d.partyid)
when matched then update set t.tin = d.tin;

How to use not exists with insert?

I'm trying to frame the below query but it always gives me the error "SQL command not properly ended". How do i use it??
INSERT INTO PROGRAM_KPI (AMSPROGRAMID,MASTER_KPI_ID,LASTUPDATEDBYDATALOAD)
(SELECT 'PRG-026',MASTER_KPI_ID,to_char(sysdate,'dd-mon-yy hh.mi.ss') from kpi_master)
WHERE NOT EXISTS(select * from insight_master
where amsprogramid = V_PROGRAMID
and inamsscope = 1
and tickettype = 'INCIDENT'
and TICKETSUBMITDATE is not null);
Please try this..(Removing the brackets and formating the code)
INSERT INTO program_kpi
(amsprogramid, master_kpi_id, lastupdatedbydataload)
SELECT 'PRG-026', master_kpi_id, TO_CHAR (SYSDATE, 'dd-mon-yy hh.mi.ss')
FROM kpi_master
WHERE NOT EXISTS (
SELECT *
FROM insight_master
WHERE amsprogramid = v_programid AND inamsscope = 1
AND tickettype = 'INCIDENT'
AND ticketsubmitdate IS NOT NULL);
But What is the relation between table program_kpi and insight_master ?
There seems to be no join between the inner and outer subquery.

Why sub SQL in FROM area can't be null?

select col_1,
col_2
from tbl_a A,
tbl_b B,
( select col_1,col_2 from tbl_c where clo_c_1 <> '1' ) C
where A.col_1 = B.col_1
and A.col_2 = B.col_2
and (A.col_2 = B.col_2
or C.col_2 = A.col_2);
My environment is Oracle,when I run this SQL,if the sub SQL C hasn't got a result,then the entire SQL returns NULL.Whereas if C has a result(not null) which fits other condions,there could be a result.Would somebody explain why sub SQL at the from area need to be not NULL?Thanks very much.
You need to bring yourself into the 90s and start using standard joins:
select col_1,
col_2
from tbl_a A
inner join
tbl_b B
on A.col_1 = B.col_1
and A.col_2 = B.col_2
left join
( select col_1,col_2 from tbl_c where clo_c_1 <> '1' ) C
on
C.col_2 = A.col_2
As a guess. I'm not entirely sure what your join conditions should be but that's my first attempt.
This is expected behaviour. When you join two result sets, you only want to get results where the join criteria is satisfied. If the criteria are not satisfied, you should get no results.
If I run the query "get me all the employees older than 65, and get their departments", if there are no employees older than 65, you would not expect to get any results, even if there are some departments in the database.
SELECT emp.name, dept.dept_name
FROM emp
JOIN dept
ON (emp.dept_no = dept.dept_no)
WHERE emp.age > 65;
As the others said, if you actually want to get rows regardless of whether the subquery has any results, you need to use an outer join.

Resources