Select varchar max in Codeigniter returns unknown characters - sql

In sql management studio, it returns the text. But in codeigniter it returns something like:
n?g%'!?>?eHH!!X??HI!??
??W.
But if I changed it to varchar(8000) it returns the text.
Why?
Here's my query:
SELECT TOP(50) A.*,
RIGHT('000'+ISNULL(CONVERT(VARCHAR,A.MajorArticleCode), ''),3) AS MajorArticleCode, B.MajorArticleDesc,
RIGHT('000'+ISNULL(CONVERT(VARCHAR,A.MinorArticleCode), ''),2) AS MinorArticleCode, C.MinorArticleDesc
FROM LIB_Items A
LEFT JOIN LIB_Major_Articles B ON A.ACCode = B.ACCode AND A.MajorArticleCode = B.MajorArticleCode
LEFT JOIN LIB_Minor_Articles C ON A.ACCode = C.ACCode AND A.MajorArticleCode = C.MajorArticleCode AND A.MinorArticleCode = C.MinorArticleCode
And here's my LIB_Items table structure
LIB_Items table structure

Related

SQL Server Loop Over Records

I have a view vwDocumentLinks with data as shown below:
I have another table RiskTypes with data as below.
The link between the table & viewis : Idx25 = Risk Type and LinkDocNo = DocumentType. What I am trying to achieve is to get DocumentType in RiskTypes that's not in the view vwDocumentLinks foreach BaseValue and where Idx25 = RiskType. An example using a single BaseValue will be:
SELECT * FROM RiskTypeDocuments WHERE RiskType = 'BUSINESS LIMITED COMPANY' AND DocumentType NOT IN (SELECT LINKDOCNO FROM DBO.VWLINKS WHERE BaseValue = '00007573-1637-4B8E-9374-730AF58BCFB6')
I tried the below query and it's not working as expected. Any help will be greatly appreciated. I am a newbie in SQL
SELECT dbo.RiskTypeDocuments.DocumentType,
dbo.RiskTypeDocuments.RiskType,
dbo.vwLinks.BaseValue AS Document
FROM dbo.vwLinks LEFT OUTER JOIN
dbo.RiskTypeDocuments ON dbo.vwLinks.LinkDocNo =
dbo.RiskTypeDocuments.DocumentType AND dbo.vwLinks.Idx25 =
dbo.RiskTypeDocuments.RiskType
WHERE dbo.RiskTypeDocuments.DocumentType IS NOT NULL
ORDER BY Document
NB: I can't change the schema. I can only create views from the existing tables.
Sample Data from the two datasets: vwDocumentLinks & RiskTypeDocuments
SELECT a.DocumentType,
a.RiskType,
b.BaseValue AS Document
FROM dbo.RiskTypeDocuments as a
INNER JOIN (Select distinct Idx25, BaseValue from vwDocumentLinks) as b on b.Idx25 = a.RiskType
where a.DocumentType not in (Select LINKDOCNO from vwDocumentLinks as c where c.basevalue = b.BaseValue )
I think what you are looking for is NOT EXISTS. It takes a little to get your head around, but the idea is to have what is called a correlated subquery. The subquery is joined to the main query, hence the term correlated.
SELECT *
FROM RiskTypeDocuments
WHERE NOT EXISTS (
SELECT 1 FROM vwDocumentLinks
WHERE RiskTypeDocuments.RiskType = vwDocumentLinks.idx25
AND RiskTypeDocuments.DocumentType = vwDocumentLinks.LinkDocNo
)
If you want to retrieve the records which don't exist in the view then
Try like this
SELECT d.DocumentType,
d.RiskType,
v.BaseValue
FROM dbo.vwLinks AS v
OUTER JOIN dbo.RiskTypeDocuments d ON v.LinkDocNo = d.DocumentType AND v.vwLinks.Idx25 =d.RiskType
WHERE v.BaseValue IS NULL
ORDER BY DocumentType

Comparing Query Result With Table and Retrieve Specific Field

My Query
SELECT
stoMast.sStockistCode,
stoMast.sStateName,
stoMast.sDivision,
stateMap.sRMCode
FROM
tblRSM_State_Mapping stateMap
INNER JOIN
tblStockistMaster stoMast ON
stateMap.sStateName = stoMast.sStateName
WHERE
stateMap.sRMCode = 'MCNE04001'
and
stoMast.sDivision = 'CIDIS'
except
select
sStockistCode,
sStateName,
sDivision,
sRMCode
From
tblEntry
Again I would like to compare the query result columns
sStockistCode
sStateName
sDivision
with tblStockistMaster with the same fields
sStockistCode
sStateName
sDivision
and retrieve the STOCKIST NAME.
Don't know how to compare the above query result with the table.
Maybe you can use following SQL code used with CTE expression
;with cte as (
SELECT
stoMast.sStockistCode,
stoMast.sStateName,
stoMast.sDivision,
stateMap.sRMCode
FROM
tblRSM_State_Mapping stateMap
INNER JOIN
tblStockistMaster stoMast ON
stateMap.sStateName = stoMast.sStateName
WHERE
stateMap.sRMCode = 'MCNE04001'
and
stoMast.sDivision = 'CIDIS'
except
select
sStockistCode,
sStateName,
sDivision,
sRMCode
From
tblEntry
)
select
cte.*,
sm.sStockistName
from cte
left join tblStockistMaster as sm
on sm.sStockistCode = cte.sStockistCode and
sm.sStateName = cte.sStateName and
sm.sDivision = cte.sDivision
-- I retrieve the stockist Name
SELECT
stoMast.sStockistName,
FROM
tblRSM_State_Mapping stateMap
INNER JOIN
tblStockistMaster stoMast
ON stateMap.sStateName = stoMast.sStateName
-- I'm joining table entry If I can match
LEFT JOIN
tblEntry tbl
on tbl.sStockistCode = stoMast.sStockistName
AND tbl.sStateName = stoMast.sStateName
AND tbl.sDivision = stoMast.sDivision
AND tbl.sRMCode = stateMap.sRMCode
WHERE
stateMap.sRMCode = 'MCNE04001'
and stoMast.sDivision = 'CIDIS'
-- And The the exept thing, I don't want that got a match with the tableentry
AND COALESCE(tbl.sStockistCode, tbl.sStateName, tbl.sDivision, tbl.sRMCode) is null
I expect it is what you wanted to get. On another way please help us understand wht you come from (tables and idea of what data can be in) and the result you want. Will be easier to create a query.

MSSQL 2012 - Why is AVG & TRY_CONVERT not returning the correct value?

I am using MSSQL 2012 and I am trying to use AVG together with TRY_CONVERT on a table column with the following datatype: nvarchar(255), NOT NULL
First before I try to query using AVG & TRY_CONVERT, this is the data that I want to get the AVG value out of using this query:
And this is the results after using AVG and TRY_CONVERT, 0 rows returned.
I also tried to use a subquery then i got 18 row returned, but with value NULL, i skipped out on AVG just to see if i was getting the correct values.. but it seems not, i also included the p.serialnumber column to show that its the correct rows that was returned, its just the value NULL that somehow appears after TRY_CONVERT.
UPDATE!:
When I execute the query below which target data that has a "." separator (qtv2.qtv_qteid = 58 (instead of 63)) , it works! So the issue is the "," separator. Anyone know solution to this??
declare #ProjectSelection nvarchar(10)
set #ProjectSelection = 'C82007588'
SELECT AVG(TRY_CONVERT(numeric(10,5), avgcap))
FROM
(
select qtv2.qtv_result as avgcap
from ProductionOrder PO
left join CustomerOrder co on co.CustomerOrderId=po.customerorderid
left join ProductionOrderProperty pop on pop.ProductionOrderId=po.productionorderid
left join product p on p.ProductionOrderId=po.productionorderid
left join QualityTestValues qtv on qtv.qtv_productid=p.ProductId
left join QualityTestValues qtv2 on qtv2.qtv_productId=p.ProductId
where pop.Value=#ProjectSelection and pop.name = 'project' and po.ProductTypeId = 1
and qtv2.qtv_qteid = 58 and qtv2.qtv_valid = 1 and qtv.qtv_ProductSegmentId = 144 and qtv.qtv_valid = 1
and qtv.qtv_qteid = 51 and qtv.qtv_result = 'J'
group by co.CustomerName, pop.Value, qtv2.qtv_result, p.SerialNumber
) A
Result:
(No column name)
22.200000
How about your compatibility level? A similar question can be found here:
TRY_CONVERT fails on SQL Server 2012
Although your server version is 2012, a lower compatibility level can cause the try_convert to be unavailable for use in your database. You can check this by running the following code in your specific database and afterwards on for instance the master database.
DECLARE #b VARCHAR(10) = '12312'
SELECT TRY_CONVERT(INT,#b)
You can take your first query and do something like this:
SELECT AVG(TRY_CONVERT(numeric(10,5), avgcap))
FROM
(
-- Insert your first query here.
) A
This should give you the average of the numbers.
EDIT
Here is a workable example that should return 24.000000.
SELECT AVG(TRY_CONVERT(numeric(10,5), A))
FROM
(
SELECT '22.5' AS A
UNION
SELECT '23.5' AS A
UNION
SELECT '26.0' AS A
) B
I found out the solution, using TRY_PARSE instead of TRY_CONVERT.
DECLARE #ProjectSelection nvarchar(10)
SET #ProjectSelection = 'C82007588'
SELECT AVG(avgcap) as avgcap
FROM
(
SELECT qtv2.qtv_result, TRY_PARSE( qtv2.qtv_result AS NUMERIC(10,3)) avgcap
FROM ProductionOrder PO
LEFT JOIN CustomerOrder co on co.CustomerOrderId=po.customerorderid
LEFT JOIN ProductionOrderProperty pop on pop.ProductionOrderId=po.productionorderid
LEFT JOIN product p on p.ProductionOrderId=po.productionorderid
LEFT JOIN QualityTestValues qtv on qtv.qtv_productid=p.ProductId
LEFT JOIN QualityTestValues qtv2 on qtv2.qtv_productId=p.ProductId
WHERE pop.Value=#ProjectSelection
AND pop.name = 'project'
AND po.ProductTypeId = 1
AND qtv2.qtv_qteid = 63
AND qtv2.qtv_valid = 1
AND qtv.qtv_ProductSegmentId = 144
AND qtv.qtv_valid = 1
AND qtv.qtv_qteid = 51
AND qtv.qtv_result = 'J'
GROUP BY co.CustomerName, pop.Value, qtv2.qtv_result, p.SerialNumber
) A`
Results:
avgcap
21264.850000

issue with MAX statement in t-sql code

This is the code:
Select BCPP.*
from ViewPBCPP BCPP
inner join
(
Select MBC.PC PC
,MRT.Name CT
,Max(dbo.CalcDatefromUTC(MBC.CreatedDate)) as LRDate
from TableBACC MBC
inner join TableSC.RT MRT
ON MBC.RTid = MRT.id
where MBC.Isdeleted = 'False'
and MBC.PC <> 'NULL'
Group by MBC.PC
,MRT.Name
) MBCR
ON BCPP.P_id = MBCR.PC
and BCPP.CreatedDate = MBCR.LRDate
and BCPP.CT = MBCR.CT
Now Max(dbo.CalcDatefromUTC(MBC.CreatedDate)) is actually a function
Query above works fine with Max(dbo.CalcDatefromUTC(MBC.CreatedDate))
Now when I write
Max(dbo.CalcDatefromUTC(MBC.CreatedDate)) + Min(dbo.CalcDatefromUTC(MBC.CreatedDate))
I cannot extract any values at all from this query written above
If I write just
(dbo.CalcDatefromUTC(MBC.CreatedDate))
it gives me error that it does not contained aggregate function or the group by function
I actually want this
(dbo.CalcDatefromUTC(MBC.CreatedDate))
so that I can use all the values of this function rather than just MAX values of it
How can I change this code written above to achieve my objective??
Anyone??
You can't have dbo.CalcDatefromUTC(MBC.CreatedDate) in the SELECT list as neither you can have MBC.CreatedDate because it's not in the GROUP BY list.
You can have MAX(MBC.CreatedDate) though because it uses an aggregate function (MAX) on thta column. You can also have:
dbo.CalcDatefromUTC(MAX(MBC.CreatedDate)) as LRDate
which is the same actually (although maybe a bit faster), as:
MAX(dbo.CalcDatefromUTC(MBC.CreatedDate)) as LRDate
From your comments, I assume the above is not very helpful. Perhaps grouping by MBC.CreatedDate as well is what you want:
Select BCPP.*
from ViewPBCPP BCPP
inner join
(
Select MBC.PC PC
,MRT.Name CT
,dbo.CalcDatefromUTC(MBC.CreatedDate) as LRDate
from TableBACC MBC
inner join TableSC.RT MRT
ON MBC.RTid = MRT.id
where MBC.Isdeleted = 'False'
and MBC.PC <> 'NULL'
Group by MBC.PC
,MBC.CreatedDate --- added
,MRT.Name
) MBCR
ON BCPP.P_id = MBCR.PC
and BCPP.CreatedDate = MBCR.LRDate
and BCPP.CT = MBCR.CT

sql server update from select

Following the answer from this post, I have something like this:
update MyTable
set column1 = otherTable.SomeColumn,
column2 = otherTable.SomeOtherColumn
from MyTable
inner join
(select *some complex query here*) as otherTable
on MyTable.key_field = otherTable.key_field;
However, I keep getting this error:
The column prefix 'otherTable' does
not match with a table name or alias
name used in the query.
I'm not sure what's wrong. Can't I do such an update from a select query like this?
Any help would be greatly appreciated.
(I'm using *blush* sql server 2000.)
EDIT:
here's the actual query
update pdx_projects set pr_rpc_slr_amount_year_to_date = summary.SumSLR, pr_rpc_hours_year_to_date = summary.SumHours
from pdx_projects pr join (
select pr.pr_pk pr_pk, sum(tc.stc_slr_amount) SumSLR, sum(tc.stc_worked_hours) SumHours from pdx_time_and_cost_from_rpc tc
join pdx_rpc_projects sp on tc.stc_rpc_project_id = sp.sol_rpc_number
join pdx_rpc_links sl on sl.sol_fk = sp.sol_pk
join pdx_projects pr on pr_pk = sl.pr_fk
where tc.stc_time_card_year = year(getdate())
group by pr_pk
) as summary
on pr.pr_pk = summary.pr_pk
and the actual error message is
Server: Msg 107, Level 16, State 2,
Line 1 The column prefix 'summary'
does not match with a table name or
alias name used in the query.
I submit to you this altered query:
update x
set x.pr_rpc_slr_amount_year_to_date = summary.sumSLR,
x.pr_rpc_hours_year_to_date = summary.sumHours
from pdx_projects x
join (
select pr.pr_pk as pr_pk,
sum(tc.stc_slr_amount) as SumSLR,
sum(tc.stc_worked_hours) as SumHours
from pdx_time_and_cost_from_rpc tc
join pdx_rpc_projects sp on tc.stc_rpc_project_id = sp.sol_rpc_number
join pdx_rpc_links sl on sp.sol_pk = sl.sol_fk
join pdx_projects pr on sl.pr_fk = pr.pr_pk
where tc.stc_time_card_year = year(getdate())
group by pr.pr_pk
) as summary
on x.pr_pk = summary.pr_pk
Notably different here: I don't re-use the alias pr inside and outside of the complex query. I re-ordered the joins the way I like them (previously referenced table first,) and explicitly notated pr_pk in 2 places. I also changed the update syntax to use update <alias>.
Maybe not the answer you're looking for, but instead of generating hugely complex queries, I usually default to inserting the some complex query here into a table variable. Then you can do a simple update to MyTable with a join to the table variable. It may not be quite as efficient, but its much easier to maintain.
I couldn't replicate your error using SQL 2008 in 80 compatibility level. While this option doesn't guarantee that I'll get the same results as you, nothing appears to be out of place.
create table pdx_projects
(
pr_rpc_slr_amount_year_to_date varchar(max)
, pr_rpc_hours_year_to_date varchar(max)
, pr_pk varchar(max)
)
create table pdx_time_and_cost_from_rpc
(
stc_slr_amount decimal
, stc_worked_hours decimal
, stc_rpc_project_id varchar(max)
, stc_time_card_year varchar(max)
)
create table pdx_rpc_projects
(
sol_rpc_number varchar(max)
, sol_pk varchar(max)
)
create table pdx_rpc_links
(
sol_fk varchar(max)
, pr_fk varchar(max)
)
update pdx_projects
set
pr_rpc_slr_amount_year_to_date = summary.SumSLR
, pr_rpc_hours_year_to_date = summary.SumHours
from
pdx_projects pr
join (
select pr.pr_pk pr_pk
, sum(tc.stc_slr_amount) SumSLR
, sum(tc.stc_worked_hours) SumHours
from pdx_time_and_cost_from_rpc tc
join pdx_rpc_projects sp on tc.stc_rpc_project_id = sp.sol_rpc_number
join pdx_rpc_links sl on sl.sol_fk = sp.sol_pk
join pdx_projects pr on pr_pk = sl.pr_fk
where tc.stc_time_card_year = year(getdate())
group by pr_pk
) as summary
on pr.pr_pk = summary.pr_pk