SQL QUERY SEARCH EACH WORDS, SPLIT SPACE - sql-server-2005

question for sql server query.
I try to create a query for searching every word on a sendence. words are split by a space.
The result contain lines that the value contain every word not at least 1.
sample:
DECLARE #DATATABLE TABLE (ID INT,COL1 VARCHAR(MAX))
INSERT INTO #DATATABLE (ID,COL1) VALUES (1,'ALPHA')
INSERT INTO #DATATABLE (ID,COL1) VALUES (2,'ALPHA BETA')
INSERT INTO #DATATABLE (ID,COL1) VALUES (3,'ALPHA BETA CHARLIE')
INSERT INTO #DATATABLE (ID,COL1) VALUES (4,'ALPHA BETA CHARLIE DELTA')
DECLARE #TESTTABLE AS TABLE (ID INT,COL1 VARCHAR(MAX))
INSERT INTO #TESTTABLE (ID,COL1) VALUES (1,'ALPHA') -- RETURN 1,2,3,4
INSERT INTO #TESTTABLE (ID,COL1) VALUES (2,'ALPHA BETA') -- RETURN 2,3,4
INSERT INTO #TESTTABLE (ID,COL1) VALUES (3,'BETA CHARLIE ALPHA') -- RETURN 3,4
INSERT INTO #TESTTABLE (ID,COL1) VALUES (4,'BETA DELTA') -- RETURN 4
INSERT INTO #TESTTABLE (ID,COL1) VALUES (5,'CHARLIE') -- RETURN 3,4
SELECT * FROM #DATATABLE
DECLARE #I AS INT
SET #I = 1
DECLARE #COUNTLINE AS INT
SET #COUNTLINE = (SELECT MAX(ID) FROM #TESTTABLE )
DECLARE #CURRENTVALUE AS VARCHAR(MAX)
WHILE(#I <= #COUNTLINE)
BEGIN
SET #CURRENTVALUE = (SELECT COL1 FROM #DATATABLE WHERE ID = #I)
-- ** TODO **
-- QUERY SHOULD RETURN EVERY LINE CONTAINING EACH WORD OF THE CURRENT TEST VALUE
SELECT * FROM #DATATABLE WHERE COL1 LIKE #CURRENTVALUE
SET #I = #I + 1
END
I write "TODO" where I put the first test (saw what that shouldn't do).
I cant create SP or Function.
I look on my side for "with" and "in" or something else.
tank for any tips
and good week end

Related

SQL Server : procedure tables cannot insert value null

I want to add 100 storages in a table.
This is my procedure:
CREATE PROCEDURE [add100*sTORAGE]
AS
DECLARE #i int, #start DATETIME, #end DATETIME
SET #start = GETDATE()
SET #i = 1
WHILE #i < 101
BEGIN
INSERT INTO Storage(storage_name)
VALUES (CONCAT('Nume', CONVERT(nvarchar, #i)))
SET #i = #i +1
END
SET #end = GETDATE()
DECLARE #testID INT = (SELECT TOP 1 (TestRunID)
FROM TestRuns
ORDER BY TestRunID DESC)
DECLARE #tableID INT = (SELECT tableID
FROM Tables
WHERE Name = 'Storage')
INSERT INTO TestRunTables (TestRunID, TableID, StartAt, EndAt)
VALUES (#testID, #tableID, #start, #end)
GO
I get an error after its execution:
Msg 515, Level 16, State 2, Procedure add100*sTORAGE, Line 13
Cannot insert the value NULL into column 'TestRunID', table 'OnlineShop.dbo.TestRunTables'; column does not allow nulls. INSERT fails.
When I look in the table, it has been created 99 columns.
I have some empty tables in a relation and this are the inserts of it (maybe here is the cause):
--INSERTS--
-- insert views into "Views"
INSERT INTO Views(Name) VALUES ('View1')
INSERT INTO Views(Name) VALUES ('View2')
INSERT INTO Views(Name) VALUES ('View3')
select * from views
delete from views where ViewID>1
-- insert into "Tests"
INSERT INTO Tests(Name) VALUES ('[add100*Storage-runView1-del100*Storage]')
INSERT INTO Tests(Name) VALUES ('[add100*Product-runView2-del100*Product]')
INSERT INTO Tests(Name) VALUES ('[add100*OrderProduct-runView3- del100*OrderProduct]')
SELECT * FROM Tests
--insert into tables
INSERT INTO Tables(Name) VALUES ('Table1')
INSERT INTO Tables(Name) VALUES ('Table2')
INSERT INTO Tables(Name) VALUES ('Table3')
SELECT * from Tables
-- insert into "testTable"
INSERT INTO TestTables(TestID, TableID, NoOfRows, Position) VALUES (1,1,100,1)
INSERT INTO TestTables(TestID, TableID, NoOfRows, Position) VALUES (3,2,100,1)
INSERT INTO TestTables(TestID, TableID, NoOfRows, Position) VALUES (2,3,100,1)
SELECT * FROM TestTables
-- insert into "testViews"
INSERT INTO TestViews(TestID,ViewID) VALUES (1,1)
INSERT INTO TestViews(TestID,ViewID) VALUES (3,2)
INSERT INTO TestViews(TestID,ViewID) VALUES (2,3)
SELECT * FROM TestViews
What's wrong? Thank you.
The error tells you everything--table TestRunTables has column "TestRunID" which requires that field to have a value. You either need to be sure to insert a value into that field, or alter the column so that it will use a default value when you don't specify it.
This line:
DECLARE #testID INT = (SELECT TOP 1 (TestRunID) FROM TestRuns ORDER BY TestRunID DESC)
will set #testID to null if no records are returned from TestRuns or if the first TestRunID is null. This is probably what you need to fix.

Get Scope identity for multiple inserts

For table1 Inserted 3 records
It should get those three identities and it should insert 3 records in table3 (but it’s not happening- it inserts 3 records with same identity ie.last scope identity)
create table table1(ID INT identity(1,1),Name varchar(50))
insert into table1 values('Ram'),('Sitha'),('Laxman')
create table table1(ID INT identity(1,1),Name varchar(50))
create table table3(ID INT ,Name varchar(50))
insert into table2(Name)
select Name from table1
declare #id int;
set #id= (select scope_Identity())
begin
insert into table3(ID,Name)
select #id,Name from table2
end
select * from table2
select * from table3
How can get all identities to insert do I need to write a loop (or) do I need to Create a trigger.
Please give me a solution I am strugguling from past 4 hours.
Thanks in anvance
Use the OUTPUT clause to handle multi-row inserts:
INSERT INTO dbo.table2(Name)
OUTPUT inserted.ID, inserted.Name INTO table3
SELECT Name FROM dbo.table1;
You can use the OUTPUT clause to get the identity from any number of inserts.
create table table1(ID INT identity(1,1),Name varchar(50))
DECLARE #T1 Table (ID int, name varchar(50))
insert into table1
OUTPUT inserted.ID, Inserted.Name INTO #T1
values('Ram'),('Sitha'),('Laxman')
DECLARE #IdentityId INT,#Count INT=1
DECLARE #temp AS TABLE (Id INT IDENTITY ,Name NVARCHAR(100))
INSERT INTO #temp(Name)
SELECT Name FROM table1
WHILE #Count <=(SELECT COUNT(SId) FROM #temp)
BEGIN
INSERT INTO table2(Name)
SELECT Name FROM #temp
WHERE Id=#Count
SET #IdentityId = SCOPE_IDENTITY()
INSERT INTO tabel3(#IdentityId,Name)
SELECT 3, #IdentityId,1,GETDATE()
SET #Count=#Count+1
END

Assign multiple values to Table variable in SQL

DECLARE #ID INT
SET #ID = (select top 1 USER_REQ_JOB_ID
from T8504_USER_REQ_JOB
where JOB_GRP_ID = 160
order by LST_UPDT_TS desc)
SELECT INPUT_PARM_VAL_TX
from TBL_RPT_JOB_INPUT_PARAM
where USER_REQ_JOB_ID = #ID
This returns these results:
USA
USCC
6
7
2
These five records what I get I want to assign to five different variables to use in stored procedure.
I was trying with table variable like this :
declare #CID table (
Region Char(3)
,Segment Char(3)
,MasterContractId int
,ctcid int
,templateid int)
insert into #CID (Region,Segment,MasterContractId,ctcid,templateid)
But how to insert that 5 rows here?
INSERT INTO #CID
select * from
(
select
'Temp' + convert(char(1), row_number() over (order by (select 0))) as columnName,
INPUT_PARM_VAL_TX as Value
from TBL_RPT_JOB_INPUT_PARAM where USER_REQ_JOB_ID = #ID
) d
pivot
(
max(value)
for columnname in (Temp1, Temp2, Temp3, Temp4, Temp5)
) piv;
See if this helps.
Take a look at this fiddle for an example.
Courtesy:
Add row number to this T-SQL query
Efficiently convert rows to columns in sql server
EDIT: The sql adds an extra column to generate row numbers to use it as an extra column, which is pivoted as column heading.
it's really gross, but one way you could probably do it is this (though you'll need to apply it to your case):
http://sqlfiddle.com/#!6/d41d8/21507
declare #table TABLE (value varchar(50))
INSERT INTO #table
VALUES ('first')
INSERT INTO #table
VALUES ('second')
INSERT INTO #table
VALUES (3)
INSERT INTO #table
VALUES (4)
DECLARE #temp TABLE (id int identity(1,1), value varchar(50))
INSERT INTO #temp
SELECT [value]
FROM #table t
SELECT *
FROM #temp
DECLARE #CID TABLE (Region varchar(50), cont varchar(50), another int, andAnother int)
INSERT INTO #CID
(
Region,
cont,
another,
andAnother
)
VALUES
(
(SELECT value FROM #temp WHERE id = 1), -- Region - varchar
(SELECT value FROM #temp WHERE id = 2), -- cont - varchar
(SELECT value FROM #temp WHERE id = 3), -- another - int
(SELECT value FROM #temp WHERE id = 4) -- andAnother - int
)
SELECT * FROM #cid
note that i assumed you're using mssql, you did not specify

Passing multiple parameters into a Table valued function

I have a table valued function as below. When I am trying to pass more than one parameter at the same time I am getting a error like "Function has too many arguments specified" .
CREATE FUNCTION [dbo].[GetCompanyUsers](#CompanyId BIGINT)
RETURNS #Users TABLE (Id BIGINT,Contact NVarchar(4000))
AS
BEGIN
INSERT INTO #Users(Id,Contact)
SELECT [Id]
,ISNULL([FirstName],'')+' ' +ISNULL([LastName],'') AS [Contact]
FROM [dbo].[CompanyAddressesContacts]
WHERE [CompanyId]=#CompanyId
ORDER BY ISNULL([FirstName],'')+' ' +ISNULL([LastName],'')
RETURN
END
What modifications I require in the above code so that it allows multiple values and I need to use the function in a "WHERE" condition in my dataset.
WHERE(Document_RFIs.CreatedBy IN
(SELECT Id FROM dbo.GetCompanyUsers(#CompanyId)))
This may help (but the fundamental problem is - passing a comma delimited string is something to be avoided unless absolutely necessary - which explains why you have received so few answers):-
--set nocount on
--create table #Document_RFIs (
-- CreatedBy varchar(50),
-- columna varchar(50),
-- columnb varchar(50),
-- columnc varchar(50)
--)
--insert into #Document_RFIs values
-- ('albert einstein','another','value',null),
-- ('marie curie','some',null,'tuna'),
-- ('isaac newton','why','not','provide'),
-- ('kepler','some','test','data'),
-- ('robert boyle','with','your','question'),
-- ('john dalton','it',null,'would'),
-- ('enrico fermi','make','helping','you'),
-- ('peter higgs','so','much','easier')
--create table #CompanyAddressesContacts (
-- companyid int,
-- firstname varchar(50),
-- lastname varchar(50)
--)
--insert into #CompanyAddressesContacts values (22,'albert','einstein')
--insert into #CompanyAddressesContacts values (23,'marie','curie')
--insert into #CompanyAddressesContacts values (23,'isaac','newton')
--insert into #CompanyAddressesContacts values (24,null,'kepler')
--insert into #CompanyAddressesContacts values (25,'robert','boyle')
--insert into #CompanyAddressesContacts values (25,'enrico','fermi')
--insert into #CompanyAddressesContacts values (26,'peter','higgs')
declare #ids varchar(1024)
set #ids='23,24,25'
create table #id (
companyid int
)
declare #pos int
while DATALENGTH(#ids)>0 begin
set #pos=charindex(',',#ids)
if #pos>0 begin
insert into #id values (left(#ids,#pos-1))
set #ids=SUBSTRING(#ids,#pos+1,DATALENGTH(#ids))
end else begin
insert into #id values (#ids)
set #ids=''
end
end
select d.*
from #Document_RFIs d
where exists(
select cac.*
from #CompanyAddressesContacts cac
join #id i on i.companyid=cac.companyid
where isnull(cac.firstname+' ','')+isnull(cac.lastname,'')=d.CreatedBy
)
--drop table #id
--drop table #Document_RFIs
--drop table #CompanyAddressesContacts
I would do something like this:
First convert your #CompanyId to rows
WITH CompanyIds AS (
SELECT Id
FROM CompanyTable -- Same as the source of the #CompanyId
WHERE Id IN (#CompanyId)
)
Then extract all users
,Users AS (
SELECT UserId
FROM CompanyIds
CROSS APPLY (
SELECT Id AS UserId
FROM dbo.GetCompanyUsers(CompanyIds.Id)
) AS CA1
)
And then use it in the where statement
WHERE Document_RFIs.CreatedBy IN (SELECT UserId
FROM Users)

How to delete duplicate rows from table from DbVisualiser

I have a table called ORG_MAP, it contained 200 records, I executed a query to copy those 200 records to other table called ORG_MAP_1 (duplicate table of ORG_MAP), but what happened was the same 200 records got inserted into the same ORG_MAP table.
Now I want to remove those duplicated records. I don't know how to do that.
Please help me. I'm using db visualizer8.0.11 version.
the query I used was:
INSERT INTO METRICS.ORG_MAP (REPORT_END_DATE,ENTITY,ENTITY_TYPE,RELATIONSHIP,TARGET,TARGET_TYPE)
SELECT REPORT_END_DATE,ENTITY,ENTITY_TYPE,RELATIONSHIP,TARGET,TARGET_TYPE
FROM METRICS.ORG_MAP
i dont think there is any direct solution for your problem
but i have done some work around may be useful for you....
create table #table(id int,c varchar(2))
insert into #table values('1','a')
insert into #table values('1','a')
insert into #table values('2','b')
insert into #table values('2','b')
insert into #table values('3','c')
insert into #table values('3','c')
insert into #table values('4','d')
insert into #table values('5','d')
declare #table table(uid int,id int ,c varchar(2));
with tbl as (
select ROW_NUMBER() OVER(ORDER BY id DESC) AS uid ,id,c from #table
)
insert into #table select * from tbl
declare #tmpid int,#tmpuid int,#cnt int
declare tmpc cursor
for select uid,id from #table;
open tmpc
fetch next from tmpc
into #tmpuid,#tmpid
while ##FETCH_STATUS = 0
BEGIN
set #cnt = (select COUNT(id) from #table where id = #tmpid)
IF (#cnt > 1)
BEGIN
delete from #table where uid = #tmpuid
END
fetch next from tmpc
into #tmpuid,#tmpid
END
CLOSE tmpc;
DEALLOCATE tmpc;
select * from #table
drop table #table