want to get values from 2003 up to today - visual-studio-2013

DECLARE #year VARCHAR(100)
SET #year = '%-2003-%'
SELECT
DISTINCT 'AR Invoice', b.user_transaction_type_code as ar_transaction_type_code, b.name_l as ar_name_l, min(transaction_nr) as ar_min_tran_nr, max(transaction_nr) as ar_max_tran_nr, MIN(transaction_text) as min_ar_transaction_text, MAX(transaction_text) as max_ar_transaction_text
FROM
ar_invoice a, user_transaction_type b
WHERE
a.user_transaction_type_id = b.user_transaction_type_id AND
transaction_text like #year
GROUP BY
b.user_transaction_type_code, b.name_l
I want to get the values from 2003 up to today?
Can someone tell me how?

If you want to get values from 2003 to today, you can use BETWEEN '2003-01-01' AND GETDATE() option in the WHERE clause.
SELECT DISTINCT 'AR Invoice', b.user_transaction_type_code AS ar_transaction_type_code,
b.name_l AS ar_name_l, min(transaction_nr) AS ar_min_tran_nr, max(transaction_nr) AS ar_max_tran_nr,
MIN(transaction_text) AS min_ar_transaction_text, MAX(transaction_text) AS max_ar_transaction_text
FROM ar_invoice a
INNER JOIN user_transaction_type b ON b.user_transaction_type_id = a.user_transaction_type_id
WHERE transaction_text BETWEEN '2003-01-01' AND GETDATE()
GROUP BY b.user_transaction_type_code, b.name_l

DECLARE #year VARCHAR(100)
SET #year = #FromYear --2003 --today
SELECT DISTINCT 'AR Invoice'
, b.user_transaction_type_code as ar_transaction_type_code
, b.name_l as ar_name_l , min(transaction_nr) as ar_min_tran_nr
, max(transaction_nr) as ar_max_tran_nr
, MIN(transaction_text) as min_ar_transaction_text
, MAX(transaction_text) as max_ar_transaction_text
FROM
ar_invoice a, user_transaction_type b
WHERE
a.user_transaction_type_id = b.user_transaction_type_id
AND
transaction_text like '%'+'-'+ #year +'-' + '%'
GROUP BY
b.user_transaction_type_code, b.name_l

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()
...

Looking for whether a row exists in a subquery

Spoiler alert: I am fairly new to Oracle.
I have four tables: enrollments, courses/sections, standards, and grades.
We are running Honor Roll. I have queries on the first three tables that add various constraints needed to meet honor roll requirements. Then we look at the grades table. If they have a valid enrollment, in a valid course, meeting valid standards, then count up their scores. If their score qty meets thresholds, then they get Honors.
This code is not optimized, and likely can be done in a far better/more compact way I'm sure -- however, it only gets run a few times a year, so I'm willing to trade off optimization in order to increase human readability, so that I can continue to learn the fundamentals. So far I have:
WITH validCC (SELECT CC.ID AS CCID,
CC.STUDENTID AS STUDENTID,
CC.SECTIONID AS SECTIONID,
CC.TERMID AS TERMID,
STUDENTS.DCID AS STUDENTSDCID
FROM CC
INNER JOIN STUDENTS ON CC.STUDENTID = STUDENTS.ID
WHERE TERMID in (2700,2701)
AND CC.SCHOOLID = 406;
), --end validCC
validCrsSect (SELECT SECTIONS.ID AS SECTIONID,
SECTIONS.DCID AS SECTIONSDCID,
SECTIONS.EXCLUDEFROMHONORROLL AS SECTHR,
COURSES.COURSE_NUMBER AS COURSE_NUMBER,
COURSES.COURSE_NAME AS COURSE_NAME,
COURSES.EXCLUDEFROMHONORROLL AS CRSHR
FROM SECTIONS
INNER JOIN COURSES ON SECTIONS.COURSE_NUMBER = COURSES.COURSE_NUMBER AND SECTIONS.SCHOOLID = COURSES.SCHOOLID
WHERE SECTIONS.TERMID IN (2700,2701)
AND SECTIONS.SCHOOLID = 406
AND SECTIONS.EXCLUDEFROMHONORROLL = 0
AND COURSES.EXCLUDEFROMHONORROLL = 0
), --end validCrsSect
validStandard (SELECT STANDARDID,
IDENTIFIER,
TRANSIENTCOURSELIST
FROM STANDARD
WHERE isActive = 1
AND YEARID = 27
AND ( instr (STANDARD.identifier, 'MHS.TS', 1 ,1) > 0 --Is a valid standard for this criteria: MHS TS
or STANDARD.identifier = 'MHTC.TS.2' --or MHTC TS
or STANDARD.identifier = 'MHTC.TS.4' )
), --end validStandard
--sgsWithChecks (
SELECT sgs.STANDARDGRADESECTIONID AS SGSID,
sgs.STUDENTSDCID as STUDENTSDCID,
sgs.STANDARDID AS STANDARDID,
sgs.STORECODE AS STORECODE,
sgs.SECTIONSDCID AS SECTIONSDCID,
sgs.YEARID AS YEARID,
sgs.STANDARDGRADE AS STANDARDGRADE,
(select count(CCID) from validCC INNER JOIN STANDARDGRADESECTION sgs ON sgs.STUDENTSDCID = validCC.STUDENTSDCID and sgs.SECTIONSDCID = validCC.SECTIONID) as CC_OK,
(select count(SECTIONID) from validCrsSection INNER JOIN STANDARDGRADESECTION sgs ON sgs.SECTIONSDCID = validCrsSect.SECTIONSDCID) AS CRS_OK,
(select count(STANDARDID) from validStandard INNER JOIN STANDARDGRADESECTION sgs ON sgs.STANDARDID = validStandard.STANDARDID) AS STD_OK
FROM STANDARDGRADESECTION sgs
The purpose of putting the 'OK' columns in the vGrades table is because the final SELECT (not included) goes through and counts up the instances of certain scores filtering by the checks.
Frustratingly, there are two IDs in both the students table and the sections table (and it's not the same data). So when I go to link everything, some tables use ID as the FK, others use DCID as the FK; and I have to pull in an extra table to make that conversion. Makes the joins more fun that way I guess.
Each individual query works on its own, but I can't get the final select count() to work to pull their data. I tried embedding the initial queries as subqueries, but I couldn't pass the studentid into them, and it would run that query for each student, instead of once at the beginning.
My current error is:
Error starting at line : 13 in command -
SECTIONS.DCID AS SECTIONSDCID,
Error report -
Unknown Command
However before it was saying unknown table and referencing the last line of the join statement. All the table names are valid.
Thoughts?
I replaced the INNER JOIN with a simple WHERE condition. This seems to work.
(SELECT COUNT (CCID) FROM validCC WHERE sgs.STUDENTSDCID = validCC.STUDENTSDCID and sgs.SECTIONSDCID = validCC.SECTIONID) as CC_OK,
(SELECT COUNT (SECTIONID) FROM validCrsSect WHERE sgs.SECTIONSDCID = validCrsSect.SECTIONSDCID) AS CRS_OK,
(SELECT COUNT (STANDARDID) FROM validStandard WHERE sgs.STANDARDID = validStandard.STANDARDID) AS STD_OK
I removed the stray comma at the end of validStandard and replaced from validCrsSection with from validCrsSect (assuming it was meant to refer to that WITH clause and there isn't another validCrsSection table). I am also guessing that the counts are meant to be keyed to the current sgs row and not counts of the whole table. I make it this:
with validcc as
( select cc.id as ccid
, cc.studentid
, cc.sectionid
, cc.termid
, st.dcid as studentsdcid
from cc
join students st on st.id = cc.studentid
where cc.termid in (2700, 2701)
and cc.schoolid = 406
)
, validcrssect as
( select s.id as sectionid
, s.dcid as sectionsdcid
, s.excludefromhonorroll as secthr
, c.course_number
, c.course_name
, c.excludefromhonorroll as crshr
from sections s
join courses c
on c.course_number = s.course_number
and c.schoolid = s.schoolid
where s.termid in (2700, 2701)
and s.schoolid = 406
and s.excludefromhonorroll = 0
and c.excludefromhonorroll = 0
)
, validstandard as
( select standardid
, identifier
, transientcourselist
from standard
where isactive = 1
and yearid = 27
and ( instr(standard.identifier, 'MHS.TS', 1, 1) > 0
or standard.identifier in ('MHTC.TS.2','MHTC.TS.4') )
)
select sgs.standardgradesectionid as sgsid
, sgs.studentsdcid
, sgs.standardid
, sgs.storecode
, sgs.sectionsdcid
, sgs.yearid
, sgs.standardgrade
, ( select count(*) from validcc
where validcc.studentsdcid = sgs.studentsdcid
and validcc.sectionid = sgs.sectionsdcid ) as cc_ok
, ( select count(*) from validcrssect
where validcrssect.sectionsdcid = sgs.sectionsdcid ) as crs_ok
, ( select count(*) from validstandard
where validstandard.standardid = sgs.standardid ) as std_ok
from standardgradesection sgs;
This works with the six table definitions reverse-engineered as:
create table students
( id integer not null
, dcid integer );
create table cc
( id integer
, studentid integer
, sectionid integer
, termid integer
, schoolid integer );
create table courses
( course_number integer
, course_name varchar2(30)
, excludefromhonorroll integer
, schoolid integer );
create table sections
( id integer not null
, dcid integer
, excludefromhonorroll integer
, termid integer
, schoolid integer
, course_number integer );
create table standard
( standardid integer
, identifier varchar2(20)
, transientcourselist varchar2(50)
, isactive integer
, yearid integer );
create table standardgradesection
( standardgradesectionid integer
, studentsdcid integer
, standardid integer
, storecode integer
, sectionsdcid integer
, yearid integer
, standardgrade integer );

How do I pass a parameter into the Query.CommandText in SQL Server Reporting Services?

I have the following query against an Oracle database:
select * from (
select Person.pId, Person.lastName as patLast, Person.firstName as patFirst
, Person.dateOfBirth
, Medicate.mId, Medicate.startDate as medStart, Medicate.description
, cast(substr(Medicate.instructions, 1, 50) as char(50)) as instruct
, ml.convert_id_to_date(Prescrib.pubTime) as scripSigned
, max(ml.convert_id_to_date(Prescrib.pubTime)) over (partition by Prescrib.pId, Prescrib.mId) as LastScrip
, UsrInfo.pvId, UsrInfo.lastName as provLast, UsrInfo.firstName as provFirst
from ml.Medicate
join ml.Prescrib on Medicate.mId = Prescrib.mId
join ml.UsrInfo on Prescrib.pvId = UsrInfo.pvId
join ml.Person on Medicate.pId = Person.pId
where Person.isPatient = 'Y'
and Person.pStatus = 'A'
and Medicate.xId = 1.e+035
and Medicate.change = 2
and Medicate.stopDate > sysdate
and REGEXP_LIKE(Medicate.instructions
, ' [qtb]\.?[oi]?\.?[dw][^ayieo]'
|| '|[^a-z]mg?s'
|| '|ij'
|| '|[^a-z]iu[^a-z]'
|| '|[0-9 ]u '
|| '|[^tu]hs'
, 'i')
order by ScripSigned desc
) where scripSigned = lastScrip and scripSigned > date '2011-01-01'
I have a Report Parameter defined, DateBegin, defined as a DateTime, and I've associated it with a Query Parameter also called DateBegin. I just can't figure out how to replace "date '2011-01-01'" with "DateBegin" so that the blinkin' thing actually works. Thanks!
Use the Oracle format for parameters - so use the following:
) where scripSigned = lastScrip and scripSigned > :DateBegin
(The # sign is used in SQLServer to identify SQLServer variables.)

Problem with text datatype and UDF

I have this great function that parses a field into a pivot table consisting of four columns so I can sort my table accordingly. My only problem now is I can't use the function in a query that also calls a "text" datatype to be displayed in the results. Query runs fine as long as I don't include "spName" which is a "text" datatype. I've tried using cast and convert but neither built-in functions work in this query. thanks.
error:
Pivot grouping columns must be comparable. The type of column "spName" is "text", which is not comparable.
query:
SELECT title, recID, spName, [1] AS [Col1], [2] AS [Col2],[3] AS [Col3],[4] AS [Col4]
FROM (select title, recID, spName from TestTable) t CROSS APPLY dbo.GetNumbers(title) PIVOT (MAX(num) FOR idx IN ([1], [2],[3],[4]) ) AS PivotTable ORDER BY Col1
udf:
CREATE FUNCTION GetNumbers
(
#Numbers NVARCHAR(2000)
)
RETURNS #Results TABLE
(
idx INT IDENTITY(1,1),
num INT
)
AS
BEGIN
DECLARE #NonNumericIndex INT, #NumericIndex INT
SET #NumericIndex = PATINDEX('%[0-9]%',#Numbers)
IF (#NumericIndex > 4) --First Column not there
INSERT INTO #Results VALUES (NULL)
WHILE #NumericIndex > 0
BEGIN
SET #Numbers = RIGHT(#Numbers,LEN(#Numbers)-#NumericIndex+1)
SET #NonNumericIndex = PATINDEX('%[^0-9]%',#Numbers)
IF(#NonNumericIndex = 0)
BEGIN
INSERT
INTO #Results VALUES (#Numbers)
RETURN
END
ELSE
INSERT
INTO #Results VALUES
(LEFT(#Numbers,#NonNumericIndex-1))
SET #Numbers = RIGHT(#Numbers,LEN(#Numbers)-#NonNumericIndex+1)
SET #NumericIndex = PATINDEX('%[0-9]%',#Numbers)
END
RETURN
END
sample data
title recid spname
QW 1 RT 309-23-1 1 This is title 1 words
QW 1 RT 29-1 2 this is title 2 desc
QW 1 RT 750-1 3 This is title 3
QW RT 750-1 4 This is title 4 words
The Text datatype is deprecated and sounds a dubious choice for a name field in any event.
This works for me
IF OBJECT_ID('tempdb..#TestTable') IS NULL
BEGIN
CREATE TABLE #TestTable
(
recid INT PRIMARY KEY,
title VARCHAR(50),
spName TEXT
)
INSERT INTO #TestTable
SELECT 1 AS recid, 'QW 1 RT 309-23-1' AS title, CAST('test1' AS TEXT) AS spName UNION ALL
SELECT 2 AS recid, 'QW 1 RT 29-1', CAST('test' AS TEXT) AS spName UNION ALL
SELECT 3 AS recid, 'QW 1 RT 750-1', CAST('test' AS TEXT) AS spName UNION ALL
SELECT 4 AS recid, 'QW RT 750-1' , CAST('test' AS TEXT) AS spName
END
SELECT recid, title, spName, [1] AS [COLUMN 1], [2] AS [COLUMN 2],[3] AS [COLUMN 3],[4] AS [COLUMN 4]
FROM
(SELECT recid, title, CAST(spName AS VARCHAR(MAX)) AS spName FROM #TestTable ) T
CROSS APPLY dbo.GetNumbers(title)
PIVOT
(MAX(num) FOR idx IN ([1], [2],[3],[4])
) AS PivotTable;

How to get the last element by date of each "type" in LINQ or TSQL

Imagine to have a table defined as
CREATE TABLE [dbo].[Price](
[ID] [int] NOT NULL,
[StartDate] [datetime] NOT NULL,
[Price] [int] NOT NULL
)
where ID is the identifier of an action having a certain Price. This price can be updated if necessary by adding a new line with the same ID, different Price, and a more recent date.
So with a set of a data like
ID StartDate Price
1 01/01/2009 10
1 01/01/2010 20
2 01/01/2009 10
2 01/01/2010 20
How to obtain a set like the following?
1 01/01/2010 20
2 01/01/2010 20
In SQL, there are several ways to say it. Here's one that uses a subquery:
SELECT *
FROM Price p
WHERE NOT EXISTS (
SELECT *
FROM Price
WHERE ID = p.ID
AND StartDate > p.StartDate
)
This translates fairly trivially to LINQ:
var q = from p in ctx.Price
where !(from pp in ctx.Price
where pp.ID == p.ID
&& pp.StartDate > p.StartDate
select pp
).Any()
select p;
Or should I say, I think it does. I'm not in front VS right now, so I can't verify that this is correct, or that LINQ will be able to convert it to SQL.
Minor quibble: Don't use the name ID to store a non-unique value (the type, in this case). It's confusing.
Assuming ID & StartDate will be unique:
SELECT p.ID, p.StartDate, p.Price
FROM Price p
JOIN
(
SELECT ID, MAX(StartDate) AS LatestDate
FROM Price
GROUP BY ID
) p2 ON p.ID = p2.ID AND p.StartDate = p2.LatestDate
Since you tagged your question with LINQ to SQL, here is an LINQ query to express what you want:
from price in db.Prices
group price by price.Id into group
let maxDateInGroup = group.Max(g => g.StartDate)
let maxDatePrice = group.First(g => g.StartDate == maxDateInGroup)
select
{
Id = group.Key,
StartDate = maxDatePrice.StartDate,
Price = maxDatePrice.Price
};

Resources