Given that kind of syntax
SELECT 'all the left part of 'email' column before #'
FROM [dbname].[tablename]
How to insert the SELECT query into a new column called 'email_left'?
PS. for simplicity I do not show the long query after my select query.
it is an update:
UPDATE x
SET [new column created outside this statement] = 'all the left part of "email" column before #'
FROM [dbname].[tablename] AS x
another solution - computed column
ALTER TABLE dbo.table_name
ADD column_name AS 'all the left part of ' + email + ' column before #'
GO
update -
IF OBJECT_ID('dbo.email', 'U') IS NOT NULL
DROP TABLE dbo.email
GO
SELECT email
INTO dbo.email
FROM [dbname].[tablename]
GO
--CREATE CLUSTERED INDEX index_name ON dbo.email (email)
Related
create table test(columnname varchar(100))
CREATE or replace TABLE brand(
Brand VARCHAR(150),
Day DATE,
Users VARCHAR(150)
);
SELECT array_agg(column_name)
FROM information_schema.columns
where table_name = 'brand';
using this query i am getting a single line, but to insert it as row
excepted output:
select * from test
columnname
Brand
Day
Users
If you want many values from you ‘test’ table when you select from the information schema don't use array_agg to turn the many rows into a single line.
To insert:
insert into test
SELECT column_name
FROM information_schema.columns
where table_name = 'brand';
I have this query :
SELECT
c.violatorname
FROM
dbo.crimecases AS c,
dbo.people AS p
WHERE
REPLACE(c.violatorname, ' ', '') = CONCAT(CONCAT(CONCAT(p.firstname, p.secondname), p.thirdname), p.lastname);
The query is very slow, I need to create an index on violatorname column with replace function. Any ideas?
I would suggest you to add computed columns and create index on it.
ALTER TABLE crimecases
ADD violatornameProcessed AS Replace(violatorname, ' ', '') PERSISTED
ALTER TABLE people
ADD fullName AS Concat(firstname, secondname, thirdname, lastname) PERSISTED
Persisted will store the computed data on the disk instead of computing every time. Now create index on it.
CREATE INDEX Nix_crimecases_violatornameProcessed
ON crimecases (violatornameProcessed)
include (violatorname)
CREATE INDEX Nix_people_fullName
ON people (fullName)
Query can be written like
SELECT c.violatorname
FROM dbo.crimecases AS c
INNER JOIN dbo.people AS p
ON c.violatornameProcessed = p.fullName
I have two tables called 'ticket' and 'ticket_category'.
'Ticket' table has a column 'Ticket_Uid' and its type is 'UniqueIdentifier'.
Each 'ticket_uid' in 'ticket' table has one-to-many mappings in 'ticket_category' table.
E.g.
'Ticket' table:
Ticket_Uid
100
Ticket_Category:
Ticket_Uid Ticket_Category_Uid
100 ABC
100 DEF
100 XYZ
I want to create the following table named 'comment_mining':
Ticket_Uid Category_List
100 ABC,DEF,XYZ
The table has already been created using the following:
create table dbo.comment_mining
(
Ticket_UID [uniqueidentifier] NOT NULL,
time_created datetime,
time_closed datetime,
total_time_taken int,
category_list nvarchar(500),
comment_list varchar(8000)
);
I have already created this table and populated the 'Ticket_Uid' column.
For inserting into the 'category_list' column, I am using the following query:
insert into dbo.comment_mining(category_list)
SELECT
(SELECT distinct convert(varchar(500),category_id) + ',' AS [text()]
FROM ticket_category pr
WHERE pr.ticket_uid = p.ticket_uid
FOR XML PATH (''))
AS Category_list
FROM comment_mining p
When I run the above query, it gives me the following error:
Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'Ticket_UID', table 'Support_Saas.dbo.comment_mining'; column does not allow nulls. INSERT fails.
The statement has been terminated.
(which is strange as I am not even inserting in the 'Ticket_Uid' column)
When I run the same query without the insert statement, it executes perfectly. The query is as follows:
SELECT
(SELECT distinct convert(varchar(500),category_id) + ',' AS [text()]
FROM ticket_category pr
WHERE pr.ticket_uid = p.ticket_uid
FOR XML PATH (''))
AS Category_list
FROM comment_mining p
Yes there are some NULL values when the above query is run, but 'category_list' column in 'comment_mining' table can take NULL values. Why is the error on 'ticket_Uid' column?
Would someone please be able to explain why this is happening and what's the cure to this?
P.S. - I am new to SQL.
The reason you have the insert error on table comment_mining is because you set the Ticket_Uid column as not null; however, since it does not have a default value, the insert fails because whether you're inserting that field specifically or not, when a row is created, all columns must be filled in or be null.
You can do one of 2 things:
Change the structure of the comment_mining table to have a default value for Ticket_Uid (You can do this in the table designer or with code:
Example 1:
Alter Table comment_mining
Add Constraint DF_CommentMining_1 default NewID() for Ticket_UID
Make your insert explicitly include a generated uniqueidentifier (GUID) value by using the SQL NewID() function to populate the Ticket_UID UniqueIdentifier column
Example 2:
insert into dbo.comment_mining(Ticket_Uid, category_list)
SELECT NewID(),
[ your subquery ]...
In both cases, you're now satisfying the NOT NULL constraint on comment_mining.Ticket_UID, either by making it automatically populate itself, or by supplying a value.
try this,
;with cte as
(
select 100 Ticket_Uid,'ABC' Ticket_Category_Uid union all
select 100 , 'DEF' union all
select 100, 'XYZ'
)
select distinct b.Ticket_Uid,
stuff((select ','+a.Ticket_Category_Uid from cte a where a.Ticket_Uid=b.Ticket_Uid for xml path('')),1,1,'')
from cte b
In a forum application, the actual name of the thread is stored in a table, and then replies is stored in another table.
Table_Thread
Subject varchar(255) e.g. "How to setup fulltext search"
Table_Replies (users replies here)
ReplyText text(not null)
Now I want to create a full-text search on both the subject and reply columns, but they seem very related so they should be in the same index.
Is it possible to do this?
I'm using sql server 2005.
Assuming there is an association between the subject and the replies you could create a view WITH SCHEMABINDING, create a UNIQUE CLUSTERED index on the view and then add that view to your fulltext catalog selecting the two columns you want included.
When huge concurrent query requests come, RDBMS cannot afford it by SQL. what's more, select SQL supports full-text search badly. So you need IR (Information Retrieval) library such as Lucene for java.
You could create a indexed view containing an union of both indexed columns + PK of the tables
e.g.
CREATE VIEW SearchText
WITH SCHEMABINDING
AS SELECT * FROM (
(Subject as Text, Table_Thread_ID as ID, 1 as Type FROM Table_Thread)
UNION ALL
(ReplyText as Text, Table_Replies_ID as ID, 2 as Type FROM Table_Replies));
I put type 1 and 2 as arbitrary, since you need a unique key to build a fulltext index.
And then create a unique index on (ID, Type), and finally your fulltext index.
CREATE UNIQUE INDEX SearchText_UK ON SearchText (ID, Type);
CREATE FULLTEXT CATALOG ft AS DEFAULT;
CREATE FULLTEXT INDEX ON SearchText(Text)
KEY INDEX SearchText_UK
WITH STOPLIST = SYSTEM;
I have seen what NopCommerce (C# MVC Open Source E-Commerce) has done using fulltext search on 'products' and 'variants' and only return 'products'. This is very similar to your case because you want to search on 'Thread' and 'Replies' but you obviously want to only return 'threads'. I have change it to use threads and replies for you:
First, create a function that generates an index name by table (optional):
CREATE FUNCTION [dbo].[nop_getprimarykey_indexname]
(
#table_name nvarchar(1000) = null
)
RETURNS nvarchar(1000)
AS
BEGIN
DECLARE #index_name nvarchar(1000)
SELECT #index_name = i.name
FROM sys.tables AS tbl
INNER JOIN sys.indexes AS i ON (i.index_id > 0 and i.is_hypothetical = 0) AND (i.object_id=tbl.object_id)
WHERE (i.is_unique=1 and i.is_disabled=0) and (tbl.name=#table_name)
RETURN #index_name
END
GO
Then, enable fulltext by creating the catalog and the indexes:
EXEC('
IF NOT EXISTS (SELECT 1 FROM sys.fulltext_catalogs WHERE [name] = ''myFullTextCatalog'')
CREATE FULLTEXT CATALOG [myFullTextCatalog] AS DEFAULT')
DECLARE #create_index_text nvarchar(4000)
SET #create_index_text = '
IF NOT EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE object_id = object_id(''[Table_Thread]''))
CREATE FULLTEXT INDEX ON [Table_Thread]([Subject])
KEY INDEX [' + dbo.[nop_getprimarykey_indexname] ('Table_Thread') + '] ON [myFullTextCatalog] WITH CHANGE_TRACKING AUTO'
EXEC(#create_index_text)
SET #create_index_text = '
IF NOT EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE object_id = object_id(''[Table_Replies]''))
CREATE FULLTEXT INDEX ON [Table_Replies]([ReplyText])
KEY INDEX [' + dbo.[nop_getprimarykey_indexname] ('Table_Replies') + '] ON [myFullTextCatalog] WITH CHANGE_TRACKING AUTO'
EXEC(#create_index_text)
Then, in the stored procedure to obtain products by keywords, build a temporary table with a list of product Ids that match the keywords.
INSERT INTO #KeywordThreads ([ThreadId])
SELECT t.Id
FROM Table_Thread t with (NOLOCK)
WHERE CONTAINS(t.[Subject], #Keywords)
UNION
SELECT r.ThreadId
FROM Table_Replies r with (NOLOCK)
WHERE CONTAINS(pv.[ReplyText], #Keywords)
Now you can use the temporary table #KeywordThreads to join with the list of threads and return them.
I hope this helps.
sqlite3
I have two tables. One contains some lists and the other contains each list's items.
I want to create a select statement that grabs the rows in the lists table, but also creates a column which is a comma-delimited summary of the items in each list.
I have this working as follows:
select
master._id as _id,
master.name as name,
master.created_on as created_on,
group_concat(items.name, ', ')
from
tablea master
join
tableb items
on
master._id = items.master_id
group by
master._id
However, I would like to name the column returned by the group_concat as "summary" like so:
select
master._id as _id,
master.name as name,
master.created_on as created_on,
group_concat(items.name, ', ') as summary
from
tablea master
join
tableb items
on
master._id = items.master_id
group by
master._id
When I do this, I get an sql error:
"SQL error: near "summary": syntax error
How can I achieve what I'm wanting to do?
I would also like to order the items in the group_concat alphabetically descending, but naming the column is my first priority.
"AS" is optional. However, both with and without "AS" works fine for me (using SQLite version 3.6.14.2):
drop table tablea;
drop table tableb;
create table tablea(_id int, name varchar, created_on varchar);
create table tableb(master_id int, name varchar);
insert into tablea values(0, 'Hello', '2010');
insert into tableb values(0, 'x');
select
master._id as _id,
master.name as name,
master.created_on as created_on,
group_concat(items.name, ', ') as summary
from
tablea master
join
tableb items
on
master._id = items.master_id
group by
master._id