Insert data with a SUBSTRING in the SELECT - sql

How do I INSERT data with a SUBSTRING in the SELECT?
I tried the following, but it didn't work:
INSERT INTO PHONE(
ID_CLIENT,
COD,
PHONE)
SELECT (ID_CLI,
SUBSTRING(PHONE,0,3), '',
SUBSTRING(PHONE,3,9), '')
FROM [dbo].TABLE_1
WHERE ID_PHONE = 2
What am I doing wrong?

INSERT INTO PHONE(
ID_CLIENT,
COD,
PHONE)
SELECT (ID_CLI,
SUBSTRING(PHONE,0,3),
SUBSTRING(PHONE,3,9)
FROM [dbo].TABLE_1
WHERE ID_PHONE = 2

SQL is not like other languages. When counting a string, the count does not begin at zero, like python and other similar languages, it begins at 1. I noticed, in your substring() function, you inserted the starting value as 0. This would be correct in some languages, but in SQL the first character is 1 not zero. Also, after the last substring, be sure to close your () from the original select statement. You opened () after the select, before the ID_CLI column, but did not provide a closing () at the end of the statement. I am not a professional with this language, by any means, but I hope my input is helpful for what you are trying to do. I believe this may work, if not there may be something I am missing, (again, I am a novice with SQL, so forgive me if this is not correct)
INSERT INTO PHONE(
ID_CLIENT,
COD,
PHONE)
SELECT (ID_CLI,
SUBSTRING(PHONE,1,4),
SUBSTRING(PHONE,4,10))
FROM [dbo].TABLE_1
WHERE ID_PHONE = 2

It appears you are selecting five columns and trying to insert into three columns in another table. Make sure the number of rows match. It appears that you may be trying to concatenate the substrings with empty strings, which you would need to use the CONCAT function for.

You can do something like this:
WITH CteData
AS
(
SELECT ID_CLI,SUBSTRING(PHONE,0,3) AS COD,SUBSTRING(PHONE,3,9) AS PHONE
FROM [dbo].TABLE_1
WHERE ID_PHONE = 2
)
INSERT INTO PHONE(ID_CLIENT,COD,PHONE)
SELECT CteData.ID_CLI,CteData.COD,CteData.PHONE FROM CteData
but first you need to remove the empty space like '' which create the impression for the INSERT statement that you have more columns on the SELECT than the INSERT, I did use CTE just to make the code readable

Related

Using CONTAINS to find items IN a table

I'm trying to write a SP that will allow users to search on multiple name strings, but supports LIKE functionality. For example, the user's input might be a string 'Scorsese, Kaurismaki, Tarkovsky'. I use a split function to turn that string into a table var, with one column, as follows:
part
------
Scorsese
Kaurismaki
Tarkovsky
Then, normally I would return any values from my table matching any of these values in my table var, with an IN statement:
select * from myTable where lastName IN (select * from #myTableVar)
However, this only returns exact matches, and I need to return partial matches. I'm looking for something like this, but that would actually compile:
select * from myTable where CONTAINS(lastName, select * from #myTableVar)
I've found other questions where it's made clear that you can't combine LIKE and IN, and it's recommended to use CONTAINS. My specific question is, is it possible to combine CONTAINS with a table list of values, as above? If so, what would that syntax look like? If not, any other workarounds to achieve my goal?
I'm using SQL Server 2016, if it makes any difference.
You can use EXISTS
SELECT * FROM myTable M
WHERE
EXISTS( SELECT * FROM #myTableVar V WHERE M.lastName like '%'+ V.part +'%' )
Can your parser built the entire statement? Will that get you what you want?
select *
from myTable
where CONTAINS
(lastName,
'"Scorsese" OR "Kaurismaki" OR "Tarkovsky"'
)
This can be done using CHARINDEX function combined with EXISTS:
select *
from myTable mt
where exists(select 1 from #myTableVar
where charindex(mt.lastName, part) > 0
or charindex(part, mt.lastName) > 0)
You might want to omit one of the conditions in the inner query, but I think this is what you want.

Check if value is in different table

so I am new to SQL and I have little experience with it. So please excuse if this is really basic but I can't seem to find it after googling...
so I have a table which contains a serialnumber field.
I have a single inputfield which contains comma seperated values with each one being a serialnumber. I just want to display the serialnumbers that are in that comma seperated string.
So I have a splitstring function that I can use which splits the string at the commas like this:
SELECT * FROM dbo.SplitString('sn1,sn2,sn3,sn4,sn5,sn6', ',')
this returns a table with each sn being a row.
So I would want something like this:
SELECT
*
FROM
tbl_serials AS sn
WHERE
sn.serialnumber in dbo.SplitString('sn1,sn2,sn3,sn4,sn5,sn6', ',')
so this would display only the rows where the serialnumber is inside the string. But I don't know how to syntactily construct this.
Any help is appreciated
One method to do this is using join:
SELECT sn.*
FROM tbl_serials sn JOIN
dbo.SplitString('sn1,sn2,sn3,sn4,sn5,sn6', ',') as ss(val)
ON sn.serialnumber = ss.val;
With your route, you need a subquery:
SELECT sn.*
FROM tbl_serials sn JOIN
WHERE sn.serialnumber in (SELECT val
FROM dbo.SplitString('sn1,sn2,sn3,sn4,sn5,sn6', ',') as ss(val)
);
In both these cases, the as ss(val) assigns a table alias and a column alias to the value. Some versions of SplitString might return more than one value (such as a position). If you have such a version, then you need to include the extra return values as named columns.

With as in Oracle SQL

I would like to know if is it possible to use the clause "with as" with a variable and/or in a block begin/end.
My code is
WITH EDGE_TMP
AS
(select edge.node_beg_id,edge.node_end_id,prg_massif.longueur,prg_massif.lgvideoupartage,prg_massif.lgsanscable from prg_massif
INNER JOIN edge on prg_massif.asset_id=edge.asset_id
where prg_massif.lgvideoupartage LIKE '1' OR prg_massif.lgsanscable LIKE '1')
,
journey (TO_TOWN, STEPS,DISTANCE,WAY)
AS
(SELECT DISTINCT node_beg_id, 0, 0, CAST(&&node_begin AS VARCHAR2(2000))
FROM EDGE_TMP
WHERE node_beg_id = &&node_begin
UNION ALL
SELECT node_end_id, journey.STEPS + 1
, journey.DISTANCE + EDGE_TMP.longueur,
CONCAT(CONCAT(journey.WAY,';'), EDGE_TMP.node_end_id
)
It create a string as output separated by a ; but i need to get it back as variable or table do you know how? I used a concat to retrieve data in a big string. Can i use a table to insert data
,
A need to use the result to proceed more treatment.
Thank you,
mat
No, WITH is a part of an SQL statement only. But if you describe why you need it in pl/sql, we'll can advice you something.
Edit: if you have SQL statement which produces result you need, you can assign it's value to pl/sql variable. There are several methods to do this, simpliest is to use SELECT INTO statement (add INTO variable clause into your select).
You can use WITH clause as a part of SELECT INTO statement (at least in not-too-very-old Oracle versions).

sql insert using select, case and subquery inside

select * into #transacTbl from tmpTrans
insert
select
(case when tmpT.TranStatus = 10
then(
select ID, 'Returned')
else(
select ID, 'GoodSale')
end)
from
(
select * from MainTransacSource
) as tmpT
I want to be able to insert the details of a transaction into a different table with a label if it is a returned or good sale/transaction. I did this to avoid the cursor so please avoid giving a solution using a cursor.
I know the code looks good but what I'm experiencing is that, the case statement only returns one value via subquery.
This is a simplified version of the code; I have at least 6 types of cases and should be able to insert by ROW. I hate to think that I have to repeat each case per column because the actual number of columns is about 38.
You may suggest another work-around if this doesn't fit the logic. Of course, without a cursor.
Without access to your tables and not knowing more about what precisely you want to acheive, try something like this:
select * into #transacTbl from tmpTrans
insert
select tmpT.ID,
(case when tmpT.TranStatus = 10
then 'Returned'
else 'GoodSale'
end)
from
(select * from MainTransacSource) as tmpT <OR simply MainTransacSource tmpT (maybe)>
Cheers.

Use sql to select data, then insert row in first position of result set only (not update database)

If I select a column in a table, say 10 rows, can I use SQL to insert a 'please select' row into the first position using SQL only? I want to insert it in the result set only - not the database.
First you should know this is a bad idea.
You are confusing your presentation layer and your database layer. Forcing SQL to do things like output status messages or feedback to users is an antipattern to be avoided.
That being said, if the column is of a string type (char, varchar, etc), you can do something like:
SELECT 'Please Select'
UNION ALL
SELECT TOP 10 Varcharfield
FROM Mytable
If it's numeric then no unless you cast it to a string type.
Here's something you can try:
SELECT u.YourVarcharColumnName
FROM (
SELECT 1 AS rID, 'Please select' AS YourVarcharColumnName
UNION
SELECT 2 AS rID, YourVarcharColumnName
FROM YourTableName
) u
ORDER BY u.rID;
I placed rID in place and sorted by it as an extreme-case-measure when your intended first rowset does not come out on top...
However, you should keep in mind that YourVarcharColumnName should be (as it says) a string. You'll have to convert it to a string if it's a non-string column.
As #JNK mentioned it.. I thought I should edit my post as well:
Please first try:
SELECT 'Please select' AS YourVarcharColumnName
UNION
SELECT YourVarcharColumnName
FROM YourTableName
Which is similar to what the others have posted. If you ever experience what I've been unfortunate to encounter and 'Please select' doesn't come out on top, please refer to the query I posted at the top.. Thanks!
SELECT '(Please select)'
UNION
SELECT ColumnName FROM TableName