SSMS: Create a View - sql

I am trying to create a view, but I keep getting errors.
Can anyone help me with this error?
Msg 241, Level 16, State 1, Line 9
Conversion failed when converting date and/or time from character string
Code:
CREATE VIEW RecentAlbums
AS
SELECT
Artists.ArtistName, Albums.AlbumName, Albums.ReleaseDate, Genre.Genre
FROM
Albums
INNER JOIN
Artists ON Albums.ArtistId = Artists.ArtistId
INNER JOIN
Genre ON Albums.GenreId = Genre.GenreId
WHERE
(Artists.ArtistName > DATEADD(year, - 10, GETDATE()));
SELECT * FROM RecentAlbums;
Regards

because dateadd returns datetime and you try to use in where different type columns.
you can see below article about Dateadd to understand how it works.
http://www.codefolders.com/articles/sql/date-and-time-functions/dateadd().html

Related

Getting Error when using SQL With Common Table Expression (CTE)

I am new to SQL. I am trying to use SQL CTE but I keep getting the error:
Msg 102, Level 15, State 1, Line 16
Incorrect syntax near ')'.
I am using ms-sql and reading the following blog for guide.
This is my query
WITH parents(BranchCode, SOLD,BANKERSCOUNT, [TARGET]) AS
(
SELECT MS.ParentBranchCode,
SUM(NP.SOLD) SOLD,
SUM(NP.BANKERSCOUNT) BANKERSCOUNT,
SUM(NP.[TARGET]) [TARGET]
FROM NEDLLIFEPARTICIPATION NP
INNER JOIN m_Structure MS
ON MS.BranchCode = NP.BranchCode
GROUP BY MS.ParentBranchCode, NP.Year, NP.MONTH, NP.ProductId
)
Does this give you an error? If not then it might be that you simply have not included a select statement following your common table expression. This would explain why your error is showing an issue with the closing bracket, it is just telling you (if my assumption is right) that your CTE is not being used in a query (and therefore will not compile).
WITH parents(BranchCode, SOLD,BANKERSCOUNT, [TARGET]) AS
(
SELECT MS.ParentBranchCode,
SUM(NP.SOLD) SOLD,
SUM(NP.BANKERSCOUNT) BANKERSCOUNT,
SUM(NP.[TARGET]) [TARGET]
FROM NEDLLIFEPARTICIPATION NP
INNER JOIN m_Structure MS
ON MS.BranchCode = NP.BranchCode
GROUP BY MS.ParentBranchCode, NP.Year, NP.MONTH, NP.ProductId
)
select * from parents;

SQL Server : merge using Join on Source Table fails to bind

I am writing a SQL Server Merge statement but can't seem to get the syntax correct. Would someone please take a look to see where I'm going wrong?
Any help you can give is most appreciated.
What I have is two tables that I'd like to merge (w_materialmarketprices2 and d_component). My source (d_component) table requires me to do a join to a tax table (d_tax).
Everything works fine except for when I try to add the additional tax table into my join. The reason I need the tax table is because it contains a tax rate which I don't have in my d_component table (although I do have the corresponding tax code).
My comparison criteria between w_materialmarketprices2 and d_component includes the tax rate in the calculation.
Here's my code:
MERGE [DWH].[dbo].[w_materialmarketprices2] AS A
USING
(SELECT
[comp_code], [comp_desc], [comp_o_un], [comp_type],
[comp_ccy], [comp_tx], [comp_net_price], [comp_per],
[comp_doc_date], [comp_last_update], [comp_latest],
D.[tax_rate] AS TaxRate
FROM
[DWH].[dbo].[d_component]) AS B
INNER JOIN
[DWH].[dbo].[d_tax] AS D ON D.[tax_code] = B.[comp_tx]
ON
A.[mp_comp_code] = B.[comp_code] AND A.[mp_valid_date] = B.[comp_doc_date] AND B.[comp_net_price]>0 AND A.[mp_price_inc_vat] = ROUND(((B.[comp_net_price]/B.[comp_per])*(1+TaxRate),3) AND A.[mp_budget_actual] = 'PO Actual' AND B.[comp_type] ='P100' AND (left(B.[comp_code],1)='S' OR left(B.[comp_code],1)='R')
WHEN NOT MATCHED BY TARGET
THEN
INSERT ([mp_budget_actual], [mp_comp_code], [mp_comp_desc], [mp_unit], [mp_unit_qty], [mp_qualified_supplier], [mp_ccy], [mp_price_inc_vat], [mp_valid_date], [mp_last_update], [mp_latest])
VALUES ('PO Actual', B.[comp_code], B.[comp_desc], B.[comp_o_un], 1, 'Y', B.[comp_ccy], ROUND(((B.[comp_net_price]/B.[comp_per])*(1+TaxRate),3), B.[comp_doc_date], B.[comp_last_update], B.[comp_latest])
;
The error I'm getting is:
Msg 4145, Level 15, State 1, Line 20
An expression of non-boolean type specified in a context where a condition is expected, near ','.
Msg 102, Level 15, State 1, Line 23
Incorrect syntax near 'B'.
,D.[tax_rate] AS TaxRate shows up as underlined in red so I reckon the problem is something to do with that. I also get the message
The multi-part identifier "D.tax_rate" could not be bound
Thanks for your help in advance. Honkonger.
There is no reason to use a subquery in the USING clause, ie: don't put a SELECT in there:
MERGE [DWH].[dbo].[w_materialmarketprices2] AS A
USING
[DWH].[dbo].[d_component] AS B
INNER JOIN [DWH].[dbo].[d_tax] AS D ON D.[tax_code] = B.[comp_tx]
ON
A.[mp_comp_code] = B.[comp_code] .......

XML parsing: semicolon expected - bypass bad record in SQL

I know the "XML parsing: semicolon expected" error is a data error, and not a SQL error. The first error I am trying to get rid of is the one about DTD subsets, so I am using CONVERT(xml, xml_data, 2), but then I get this:
Msg 9411, Level 16, State 1, Line 14
XML parsing: line 1, character 94, semicolon expected
I don't have access to modify the actual xml. I am querying. It is data in a table (with >1 million records, so I don't even know which record is throwing the error), received from a vendor as responses to API calls. I am trying to shred the xml in a stored procedure, in order to extract bits of data.
Is it possible to somehow bypass the records with the bad data? I am NOT processing row by row at the moment, nor do I want to.
Thanks!
I tried this, but it didn't work, either:
SELECT s.id as SessionID
, st.iD as TransmissionID
, st.TransmissionTypeID
, st.xml_data
, CONVERT(xml, replace(cast(st.xml_data as varchar(max)),'&','&'), 2) as converted_xml
, s.insertdt
, st.responsecode
INTO #Session_transmissions
FROM XML_Sessions s with (nolock)
join XML_Session_Transmissions st with (nolock) on s.id = st.tbl_Subscription_XML_SessionID
WHERE s.insertdt >= '3/1/2018`
This is what finally worked:
SELECT PrimaryKeyColumn, TRY_CONVERT(xml, VarcharColumn) AS XMLValue, VarcharColumn
FROM YourTable
WHERE TRY_CONVERT(xml, VarcharColumn) IS NULL
AND VarcharColumn IS NOT NULL;

Problems converting a char to datetime

I've written following code & im trying to search this table for rows between a specific period:
SELECT 'RWH' + P.Hospital_Number AS MRN,
P.Date_of_birth,
pd.Clinic_date AS Date_Seen,
pd.Clinic_type_No
FROM (Patient_diabetes AS pd
INNER JOIN Patients AS p ON pd.Patient_No = p.Patient_No)
INNER JOIN Staff AS s ON pd.Seen_by1_No = s.Staff_No
WHERE (((pd.Clinic_type_No)=241))
--AND hospital_number like '%63028%'
AND CONVERT(datetime,pd.Clinic_Date,121) BETWEEN '02/04/2015' AND '24/09/2015'
ORDER BY p.Date_of_birth,
pd.Clinic_date DESC
But I get the following error, any ideas how to fix this?:
Msg 242, Level 16, State 3, Line 2 The conversion of a char data type
to a datetime data type resulted in an out-of-range datetime value.
I suggest you to change:
AND CONVERT(datetime,pd.Clinic_Date,121) BETWEEN '02/04/2015' AND '24/09/2015'
To this:
AND CONVERT(date,pd.Clinic_Date,121) BETWEEN '2015-04-02' AND '2015-09-24'
I think the problem here in the BETWEEN '02/04/2015' AND '24/09/2015'
By default '24/09/2015' converts into "mm/dd/yyyy" format data. So there is no 24th month.
Try to explicitly point the format of string data:
BETWEEN CONVERT(datetime,'02/04/2015',103)
AND CONVERT(datetime,'24/09/2015',103)

SQL Server Arithmetic overflow error converting expression to data type int

I have a trigger which executes after a record is inserted into a table. The trigger basically, calls a function and passes values from the insert into it. However, while it works some times, I also keep getting the following error:
Msg 8115, Level 16, State 2, Procedure UpdateNabersRating, Line 17
Arithmetic overflow error converting expression to data type int.
The trigger is as follows:
UPDATE BMS_Snapshot SET
NABERS = dbo.SetmetricsNABERSCalculation(
60,
tbl.NetFloorArea,
tbl.ElectricityCumulative,
tbl.GasCumulative,
tbl.ElectricityCumulativeMax,
tbl.GasCumulativeMax,
tbl.ElectricityMaxTotal,
tbl.GasMaxTotal,
tbl.NaturalGasConversionCubicMetersToMJ,
tbl.SuburbId)
FROM
(SELECT
Snap.SnapshotId AS SnapshotId,
Snap.ElectricityCumulative AS ElectricityCumulative,
Snap.GasCumulative AS GasCumulative,
Building.NetFloorArea AS NetFloorArea,
Building.NABERSElecTotalMax AS ElectricityMaxTotal,
Building.NABERSGasTotalMax AS GasMaxTotal,
Building.NABERSExpiry As Expiry,
NABERSTarget.ElecCumulativeMax AS ElectricityCumulativeMax,
NABERSTarget.GasCumulativeMax AS GasCumulativeMax,
[State].NaturalGasConversionCubicMetersToMJ AS NaturalGasConversionCubicMetersToMJ,
Suburb.SuburbId AS SuburbId
FROM inserted AS Snap
INNER JOIN AST_Building AS Building ON Snap.BuildingId = Building.BuildingId
INNER JOIN ESD_Suburb AS Suburb ON Building.SuburbId = Suburb.SuburbId
INNER JOIN ESD_State AS [State] ON Suburb.StateId = [State].StateId
INNER JOIN AST_NABERSTarget NABERSTarget ON Snap.BuildingId = NABERSTarget.BuildingId AND
Snap.TimeStamp = NABERSTarget.Timestamp
/*Where Snap.SnapshotId IN (Select inserted.SnapshotId FROM inserted)*/) AS tbl
WHERE tbl.SnapshotId = BMS_Snapshot.SnapshotId AND BMS_Snapshot.Range = 1
I've been playing around with it for a while, but can't seem to put my finger on the problem, particularly given it works sometimes.
Changed, arguments on function to FLOAT, instead of INT for two of the parameters.