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>
Related
I'm currently using SQL Server 2016 with SQL_Latin1_General_CP1_CI_AI collation. As expected, queries with the letter e will match values with the letters e, è, é, ê, ë, etc because of the accent insensitive option of the collation. However, queries with a ' (U+0027) do not match values containing a ’ (U+2019). I would like to know if such a collation exists where this case would match, since it's easier to type ' than it is to know that ’ is keystroke Alt-0146.
I'm confident in saying no. The main thing, here, is that the two characters are different (although similar). With accents, e and ê are still both an e (just one has an accent). This enables you (for example) to do searches for things like SELECT * FROM Games WHERE [Name] LIKE 'Pokémon%'; and still have rows containing Pokemon return (because people haven't used the accent :P).
The best thing I could suggest would be to use REPLACE (at least in your WHERE clause) so that both rows are returned. That is, however, likely going to get expensive.
If you know what columns are going to be a problem, you could, therefore, add a PERSISTED Computed Column to that table. Then you could use that column in your WHERE clause, but display the one the original one. Something like:
USE Sandbox;
--Create Sample table and data
CREATE TABLE Sample (String varchar(500));
INSERT INTO Sample
VALUES ('This is a string that does not contain either apostrophe'),
('Where as this string, isn''t without at least one'),
('’I have one of them as well’'),
('’Well, I''m going to use both’');
GO
--First attempt (without the column)
SELECT String
FROM Sample
WHERE String LIKE '%''%'; --Only returns 2 of the rows
GO
--Create a PERSISTED Column
ALTER TABLE Sample ADD StringRplc AS REPLACE(String,'’','''') PERSISTED;
GO
--Second attempt
SELECT String
FROM Sample
WHERE StringRplc LIKE '%''%'; --Returns 3 rows
GO
--Clean up
DROP TABLE Sample;
GO
The other answer is correct. There is no such collation. You can easily verify this with the below.
DECLARE #dynSql NVARCHAR(MAX) =
'SELECT * FROM (' +
(
SELECT SUBSTRING(
(
SELECT ' UNION ALL SELECT ''' + name + ''' AS name, IIF( NCHAR(0x0027) = NCHAR(0x2019) COLLATE ' + name + ', 1,0) AS Equal'
FROM sys.fn_helpcollations()
FOR XML PATH('')
), 12, 0+ 0x7fffffff)
)
+ ') t
ORDER BY Equal, name';
PRINT #dynSql;
EXEC (#dynSql);
Table structure image atached
I have DataSet already created which has all the fields from the below query.
I am trying to concatenate First and Last Name in a report drop down parameter. I tried creating a calculated field in the DataSet, but dint work.
SELECT DISTINCT
a.DiseId,
n1.LastName,
n1.FirstName,
n1.MiddleName,
...............................
FROM Table1
I also tried creating a separate DataSet by creating the below query -
Select FirstName, lastName, convert(varchar(50),FirstName) + ' ' +
convert(varchar(50),lastName) as FullName from Table2
I can see the Concatenation result in a drop down but I get this below error, this error occured only after I created the new data set with concatenation query.
An error occurred during local report processing.
The server did not provide a meaningful reply; this might be caused by a contract mismatch, a premature session shutdown or an internal server error.
How do I go about to remove the error and create the filter??
Have you tried:
select Distinct FirstName||' '||LastName FullName from table2
Then in your first dataset, use
...where FirstName||' '||LastName = :ParameterName
or if you have multiple selections, do this
...where FirstName||' '||LastName in (:ParameterName)
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.
We've two database one is the old one which has COLLATION - SQL_Latin1_General_CP1_CI_AS and the new one with COLLATION - Latin1_General_CI_AI (probably the default one).
There's a simple Table1 (ID (int), code(nvarchar(50))) in both the databases. What I'm suppose to do is compare both the tables for its data and find the missing or extra records.
Sample data in old table has code like : 'Code1 '
Sample data in new table has code like : 'Code1 '
What I need to be able to do is compare both the data (from the 'Name' column). I'm unable to trim the data from the old table -
EXAMPLE:
SELECT LTRIM(RTRIM([Name])) from [OLDDB].dbo.Table1
returns 'Code1 ' -- NOT as expected (probably due to mis-match in charset
SELECT LTRIM(RTRIM([Name])) from [NEWDB].dbo.Table1
'Code1' -- as expected
I hope it makes sense. Besides, even if I changes the COLLATION at column level still I was not able to get the ltrim / rtrim work!
Thanks.
If the CHAR(160) is the problem, then you don't have to change collation. Just replace those CHAR(160) with proper spaces and then RTRIM will work.
SELECT LTRIM(RTRIM(REPLACE([Name], CHAR(160), ' '))) from [OLDDB].dbo.Table1
Try the below update, Hope this will fix the issue.
update [OLDDB].dbo.Table1 set Name RTRIM(replace(NAME, char(160), char(32)))
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?