I inserted the json file into my table, but how do i put in the date into my table as well? - sql

Here is how my table is turning out. All I have left to do is insert the current
date in the dateloaded:
I've been trying to add a date when the data from the JSON file is loaded into the table but don't know the correct syntax. Any help please? :)

Taken from your comment below another answer:
That didn't quite work this was the error "Column name or number of
supplied values does not match table definition."
The issue you have is related to
insert into main.jsontable
select * from...
You should never rely on the columns order. The columns you are inserting to and the columns you are reading from must match. The worst case is a wrong match by coincidence.
About bad habits to kick: SELECT with *
Change this to
insert into main.jsontable(name, surname, email, ...more columns...)
select <list your JSON "columns" here>
from...
The final step then is to include the dateloaded to this:
insert into main.jsontable(dateloaded, name, surname, email, ...more columns...)
select SYSUTCDATETIME(), <list your JSON "columns" here>
from...
UPDATE
You were told already, that posting pictures is something to avoid. It's hard to read from there, but it seems you are trying to solve this here
with(
[dateloaded] datetimeoffset,
[name] ...
This derived column will never get any value as you are not reading this out of your JSON.

You can use GETDATE(), is actual datetime.

sysdatetimeofffset() should do what you want. Line up the columns, and something like the following should work:
select *, sysdatetimeoffset() from
openjson(#PersonDetails, <etc>

Related

Change Datatype of json_value during select into so I can sum column

I have a column in a table that is json. It contains several columns within it.
Example:
Row1: "sTCounts":[{"dpsTypeTest":"TESTTRIAL","cnt":3033244.0}
Row2: "sTCounts":[{"dpsTypeTest":"TESTTRIAL","cnt":3.3}
I need to sum the cnt value for all rows in table. For instance, the above would produce a result of 3033247.3
I'm not familiar with stored procs enough to master. I thought the easiest route would be to create a temp table and extract the value into a column, and then write a query to sum the column values.
The problem is that it creates a column with datatype nvarchar(4000). It won't let me sum that column. I thought of changing the datatype but not sure how. I am trying CAST without luck.
select CAST(json AS varchar) AS JSON_VALUE(jsontext,
'$.sTCounts.cnt') AS PerfCount, TitleNumber
INTO dbo_Testing_Count0
from PerformanceTest
select sum(PerfCount)
from dbo_Testing_Count
Group by PerfCount
The error message is:
Incorrect syntax near 'jsontext'.
Any ideas? I am open to another method to sum the column or changing the datatype whichever the experts can aid on. I appreciate it.
The JSON you provide in your question is not valid... This seems to be just a fragment of a larger JSON. As your data starts with a [ you have to think of it as an array, so the simple json path '$.serviceTierCounts.cnt' won't work probably...
Try this, I've added the opening { and the closing brackets at the end:
DECLARE #mockupTable TABLE(ID INT IDENTITY, YourJson NVARCHAR(MAX));
INSERT INTO #mockupTable VALUES
(N'{"serviceTierCounts":[{"dpsType":"TRIAL","cnt":3033244.0}]}')
,(N'{"serviceTierCounts":[{"dpsType":"TRIAL","cnt":3.3}]}');
--You can read one scalar value using JSON_VALUE directly with a cast. But in this case I need to add [0]. This will tell the engine to read the first (zero-based index!) object's cnt property.
SELECT CAST(JSON_VALUE(YourJson,'$.serviceTierCounts[0].cnt') AS DECIMAL(14,4))
FROM #mockupTable
--But I think, that it's this what you are looking for:
SELECT *
FROM #mockupTable
CROSS APPLY OPENJSON(YourJson,'$.serviceTierCounts')
WITH(dpsType varchar(100)
,cnt decimal(14,4));
The WITH clause will return the object in typed columns side-by-side.
For easy proceeding, you can wrap this as a CTE and continue with the set in the following SELECT.

VBA Access Table reference in SQL query

I have been running into trouble executing SQL code in VBA Access when I refer to certain Table names.
For example,
INSERT INTO TempTable (ClientName) SELECT DISTINCT 1_1_xlsx.ClientName FROM 1_1_xlsx'<--does not work
The code works fine when I changed the Table name from 1_1_xlsx to Stuff.
INSERT INTO TempTable (ClientName) SELECT DISTINCT Stuff.ClientName FROM Stuff '<--works
I have no idea why the first query results in a syntax error and the second code is runs fine even when they refer to the same thing. I suspect it should be the naming conventions but I could not find any concrete answers.
Also, are there any ways that I could use 1_1_xlsx as my table name? Or am I just writing my query wrong?
try this:
INSERT INTO TempTable (ClientName) SELECT DISTINCT [1_1_xlsx].ClientName FROM [1_1_xlsx]
In many SQL based databases you can't have a table name or field name that starts with a number.
I suspect this is the underlying reason for your problem. Although Access will allow it, I have seen it cause problems in the past.
The problem is the number at the beginning of the table name. That is bad -- because it confuses the parser.
This is a bad table name, but SQL allows you to define table aliases. And, in this case, you don't even need to repeat the table name. So, here are two simple solutions:
INSERT INTO TempTable (ClientName)
SELECT DISTINCT ClientName
FROM 1_1_xlsx;
Or:
INSERT INTO TempTable (ClientName)
SELECT DISTINCT t.ClientName
FROM 1_1_xlsx as t
There is no reason to use the complete table name as an alias. That just makes the query harder to write and to read.

Extracting an element from a semi-colon separated varchar column

I have a table where one column is a semi-colon separated set of values. I want to query for all rows that have one of my values in that column, and extract that value as part of the result set. Eg.
MyTable
[Name], [Tags]
Bob, A;B;C
Alice, Me-X
Janet, Me-Y;A
If the values I care about are in the set [Me-X, Me-Y, Me-Z] (this is a known set, but it's not stored anywhere), I want to select the name, and the value from the Tags column. So such a select would return:
Alice, Me-X
Janet, Me-Y
Curently, it's trivial to get the records and all the tags with something like this:
SELECT [Name], [Tags] FROM MyTable WHERE [Tags] LIKE '%Me-%'
... but splitthing the Tags column and pulling out the tag is something I'm not sure how to do. I have looked around and it seems like splitting a string in SQL is less than ideal. This is exacerbated by the fact that I can't make schema changes, or add SPROCS to the DB.
Does anyone know a better way for how I might be able to go about this under these constraints?
If you just want to select the tag that you are searching for try this (this isn't actually selecting the tag value from the table but the value is in there so that is beside the point
DECLARE #myTag nvarchar(10)
SET #myTag='Me'
SELECT [Name], #myTag [Tags]
FROM MyTable
WHERE [Tags] LIKE '%;'+#myTag+ ';%' --if your tag is in the middle of the string
OR [Tags] LIKE '%;'+#myTag --if it ends with your tag
OR [Tags] LIKE #myTag+ ';%' --it it starts with your tag
----Edit
Sorry I just read the question again and noticed that you want a set of values
If you have a list of all tags, you can do:
select name, tag
from table t join
tags
on ';'+tags.tag+';' like '%;'+t.tags+';%' ;
Now that I've said that, it is a really, really, really bad idea to store lists of things in a string. SQL has this great data structure for storing lists. It is called a table. In this case, you want a junction table, with one row per name and one row per tag. I do understand that sometimes you cannot change data structures and are stuck, but if you can, introduce a junction/association table.

Replacing JSON Formatted String in SQL

I have a something like this in my table column:
{"InputDirection":0,"Mask":"AA","FormatString":null,"AutoCompleteValue":null,
"Filtered":"0123456789","AutoComplete":false,"ReadOnly":true}
What I want to do is to change A to N in "Mask":"AA" and remove "Filtered":"0123456789" if they exist. Mask could be in different forms like A9A, 'AAAA`, etc.
If it was in C# I could do it by myself by parsing it to JSON, etc but I need to do it within SQL.
I've found this article which shows how to parse JSON to Table. This gave me an idea that I can parse each field to temp table and make the changes on that and convert it back to JSON so update the actual field where I take this JSON field from. However, this looks like a cumbersome process for both me and the server.
Any better ideas?
You can use this LINK .
And then use the following code
select * into #demo from
(Select * from parseJSON('{"InputDirection":0,"Mask":"AA","FormatString":null,"AutoCompleteValue":null,
"Filtered":"0123456789","AutoComplete":false,"ReadOnly":true}
')) a
select * from #demo
--- CHANGE THE DATA HERE AS REQUIRED
DECLARE #MyHierarchy JSONHierarchy;
INSERT INTO #myHierarchy
select * from #demo;
-- USE THIS VALUE AND UPDATE YOUR JSON COLUMN
SELECT dbo.ToJSON(#MyHierarchy)
drop table #demo
I may be getting something wrong here but why can’t you simply use REPLACE to update what’s needed and LIKE to identify JSON strings that should be updated?
update table_T
set json_string = REPLACE(json_string, '"Filtered":"0123456789",', '')
where json_string like '%"Mask":"AA"%'
Not sure I understand why do you need to parse it….

How to append data from one table in another where one column is xml with sql?

Actually both tables are the same, and I just need to merge data. Problem is that one column is defined with XML shema, which is same in both tables, and for my query I am getting this error from sql server studio:
"Implicit conversion between XML types constrained by different XML schema collections is not allowed. Use the CONVERT function to run this query."
Help me writedown this query.
I have something like this:
INSERT INTO table1
SELECT * FROM table2
WHERE id NOT IN (select id from table1);
Without more info on your table structure and the xml schemas I'm not sure how much assistance I can be. That said there's an article that discusses this exact problem here
http://sqlblogcasts.com/blogs/martinbell/archive/2010/11/08/Using-XML-Schemas.aspx
And his example of using the convert statement to overcome exactly this problem is as follows.
INSERT INTO [dbo].[Test_ProductModel_Content]( [CatalogDescription] )
SELECT CONVERT(XML, [CatalogDescription] )
FROM AdventureWorks2008.Production.ProductModel
WHERE [CatalogDescription] IS NOT NULL ;
GO
Hope that helps, if not post more information and I'm sure someone can help you out.