This is my first time with SQL Server 2016. I would like to know how to create a db table from json like:
{ "column1":"int","column2":"varchar(255)","column3":"column3Type..." }
It is important to me to use JSON, cause I would like to create generic tables, which has many different columns.
I don't want to use Mongo or other document-oriented database.
What you advise in this situation?
You just need to build create table statement.
Simply:
replace '":"' with space
replace '","' with ', '
replace '{' with
'Create table tbl_name ('
replace '}' with ')'
Related
I am currently attempting to combine 2 columns into 1 using CONCAT().
I have
SELECT
ApplicationTitle,
ApplicationVersion,
CONCAT(ApplicationTitle,' ',' - ',' ',ApplicationVersion) as ApplicationName
FROM
<DataBaseName>
-- Hid DataBase name due to privacy concerns.
Now this works and gives me the result I would like, but I need to not just see the result but actually insert it into the table as a new column with those values so I can delete ApplicationTitle and ApplicationVersion. Reasoning is when exporting the information (I do not have control over how the information gets exported out), it separates ApplicationTitle from ApplicationVersion (to clarify, they are application names and application versions, but I need it into 1 column with a - divider, e.g. ApplicationTitle = SQL, ApplicationVersion = 4.0, I want ApplicationName = SQL - 4.0). I've looked online but could not find something similar that worked for my current situation due to needing to delete ApplicationTitle and ApplicationVersion after ApplicationName has been populated.
What is the best way to go about doing this. My thought was INSERT INTO command with CONCAT but that doesn't seem to work for me (I'm sure I'm missing something).
Suppose You have a table named TableName and TableName has one column name ColumnName, then you can insert row at TableName by following query:
INSERT INTO TableName
(ColumnName)
SELECT
CONCAT(ApplicationTitle, ' ', ' - ', ' ', ApplicationVersion)
FROM YourTableName
This will create a new table and insert the records how you like, but if you try to run this again with the same table name it will give an error like "table already exists":
SELECT
ApplicationTitle,
ApplicationVersion,
ApplicationName = CONCAT(ApplicationTitle,' ',' - ',' ',ApplicationVersion)
INTO <NewTableName>
FROM <DataBaseName>
We are migrating from SQL Server to Teradata database. All the views and tables are migrated. But the issue is that we aren't able to take the comments from each table.
In SQL Server we have a function called extended property which if used will get the comments from the respective tables/views. Badhri helped with providing a query for fetching the comment in Teradata in the same way but it doesn’t work in the expected way.
I tried inserting sample comments in columns and the below query is not fetching exact results. Can you please help?
Sample Query:
COMMENT ON COLUMN UtilityApp_DB.SQL_Views_Columns.ColumnNAME 'A Columnname for SQL Server!';
select 'COMMENT ON COLUMN '||trim(b.databasename)||'.'||trim(b.tablename) ||'.'||trim(b.columnname)||' IS '||''''||trim(b.commentstring)||''';'
FROM DBC.Columns b
WHERE b.CommentString IS NOT NULL
AND DatabaseName='UtilityApp_DB'
AND TableName in ('UtilityApp_DB.SQL_Views_Columns');
I created a table and tried inserting the values for the comment string in the table by copying the DBC Columns structure but still I can't get the comment string.
insert into UtilityApp_DB.commentstable (commentstring) values ('UtilityApp_DB.SQL_Views_Columns');
TableName in DBC.Columns does not include the database name and IS in your string concatenation should be AS.
SELECT 'COMMENT ON COLUMN '||trim(b.databasename)||'.'||trim(b.tablename) ||'.'||trim(b.columnname)||' AS '||''''||trim(b.commentstring)||''';'
FROM DBC.Columns
WHERE DatabaseName = 'UtilityApp_DB'
AND TableName IN ('SQL_Views_Columns');
I try to auto generate insert SQL statement from an existing table in SQLServer 2008 but I do not need all record, only a small part of them. --> I thus need to filter the generated inserts. Adding a WHERE clause when generating the insert SQL statements would do the trick but I do not know how to do it.
This article answer to my question partly (SSMS internal generator) :
What is the best way to auto-generate INSERT statements for a SQL Server table?
But it exports all the data of a table. The insert scripts generated are not sorted thus I cannot filter the row I need easily (heavy manual work).
I also tried this stored procedure here (I also had to correct a part of the procedure to make it work with SQLServer 2008 replace char(255) by varchar as explained here)
But it is still not working : I get the following error :
Msg 8169, Level 16, State 2, Line 6
Conversion failed when converting from a character string to uniqueidentifier.
Could you then give me the best way to auto generate SQL Insert in SQL server 2008 from a part of a portion of a table (thus not all the rows of the table) ?
I found a way myself using Excel.
Make needed query including WHERE clause in SSMS
Select all the result
Copy with header
Paste in Excel file here under in 4th row, 1st column
Change in macro output path
Change in cell table name
Launch macro
--> take the file generated and you have a copy of your data ready to be insert again
https://dl.dropboxusercontent.com/u/49776541/GenerateInsert.xlsm
You can use merge syntax to insert data in table based on specific condition
using merge you can also delete and update data in table.you can also do
multiple operation in single sql statement.
There is an easier way to do this, other than going through all the fuss of an excel sheet.
This will return all the data in a table (much like the GUI version) where you right click on the database and select “Tasks” then select “Generate scripts”.
However, unlike the GUI version or the “export to excel” version, with this line of code, you can specify a filter in a “WHERE” clause to return only items for a particular day, or range of days, or any other filter that would normally be used in a “WHERE” clause.
In the code below, I am using 2 simple tables. One is populated with data, the other is not. I want to transfer some or all of the data from table2 to table3. Again, I can filter by date or parts of other columns. (for example… WHERE colB LIKE 'ging%';
This will generate a string of “INSERT” statements preformed in SQL query ready to run.
Note, before running this, switch your output display in SQL server from “Grid” to “Text”.
SELECT 'INSERT', + 'INTO', + 'TestTable3', + '(', + 'colA', + ',', + 'colB', + ',', + 'colDate', + ')', + 'values', + '(', + '''', + CAST(colA AS VARCHAR(10)), + '''', + ',', + '''', + CAST(colB AS VARCHAR(10)), + '''', + ',', + '''', + CAST(DATEADD(DAY, -1, GETDATE()) AS DATE) AS 'colDate', + '''', + ')', + ';'
FROM TestTable2
WHERE colDate LIKE '2018-10-14';
GO
Here is a snippet of what this will return.
Simply copy/paste the results into a new query and run it.
Too easy.
I'd like to get data from one database..table into an UPDATE script that can be used with another database..table. Rather than doing export from DB1 into DB2, I need to run an UPDATE script against DB2.
If the above is not possible, is there a way to generate the UPDATE syntax from DB1..table1:
col1 = value1,
col2 = value2,
col3 = value3,
...
--- EDIT ---
Looking through the answers, there's an assumption that DB1 is available at the same time that DB2 is available. This is not the case. Each database will know nothing of the other. The two servers/databases will not be available/accessible at the same time.
Is it possible to script the table data into a flat file? Not sure how easy that will be to then get into an UPDATE statement.
Using a linked server and an update statement will really be your easiest solution as stated above, but I do understand that sometimes that isn't possible. The following is an example of dynamically building update statements. I am assuming there is no chance of SQL Injection from the "SourceData" table. If there is that possibility then you will need to use the same technique to build statements that use sp_executesql and parameters.
SELECT 'UPDATE UpdateTable ' +
' SET FieldToUpdate1 = ''' + SourceData.DataToUpdate1 + '''' +
' , FieldToUpdate2 = ' + CAST(SourceData.DataToUpdate2 AS varchar) +
' WHERE UpdateTable.PrimaryKeyField1 = ' + CAST(SourceData.PrimaryKey1 AS varchar) +
' AND UpdateTable.PrimaryKeyField2 = ''' + SourceData.PrimaryKey2 + ''''
FROM SourceData
Also here is a link to a blog I wrote on Generating multiple SQL statements from a query. It's a bit more simplistic than the type of statement you are trying to create, but it should give you an idea. Also here is an article I wrote on using Single Quotation Marks in SQL. Other than that you can go onto Google and search for "SQL Server Dynamic SQL" and you will get hundreds of blogs, articles, forum entries etc on the subject.
Your question needs a little more clarification to be completely understand what you are trying to accomplish, but assuming the databases are on the same server, then you should be able to do something like this using UPDATE and JOIN:
UPDATE a
SET col1 = value1, col2 = value2
FROM database1.schema.table a
JOIN database2.schema.table b
ON a.primaryKey = b.primaryKey
Alternatively, if they are on different servers, you could setup a linked server and it should work similarly.
I think you still want to INSERT from one table into another table of another database. You can use INSERT INTO..SELECT
INSERT INTO DB2.dbo.TableName(Col1, Col2, Col3) -- specify columns
SELECT Col1, Col2, Col3
FROM DB1.dbo.TableName
Assuming dbo is the schema used.
Are both databases on the same SQL-Server? In that case, use fully-qualified table names. I.e.:
Update Database1.Schema.Table
SET ...
FROM
Database2.Schema.Table
If they're not on the same server, then you can use linked servers.
I'm not sure of the SQL server syntax but you can do something like this to generate the update statement.
SELECT 'UPDATE mytable SET col1=' || col1 || ' WHERE pk=' primaryKey ||';' FROM mytable;
Obviously you'll need to escape quotes, etc. depending on the value types.
I assume this is because you can't do a normal UPDATE from a SELECT?
I have a database (MS SQL) with a column that contains a query string. I want to take that query string and move it into a column that stores some settings in Json.
I could manually do this if it was only a few columns in one database, but this is part of a major upgrade that will be pushed out to over 50 sites. I'd like to have a T-SQL script that I could run on every database to perform this task for me.
Here's a sample of what the data will look like in the first column (as a query string):
KEY1=VALUE1&KEY2=VALUE2
I'd like to format that like so:
{"KEY1":"VALUE1","KEY2":"VALUE2"}
I'd appreciate any ideas you can throw my way!
Maybe you can use this
SELECT '{"' + REPLACE(REPLACE(#x, '=', '":"'), '&', '","') + '"}'
of course #x is your column I was testing with #x = N'KEY1=VALUE1&KEY2=VALUE2'