SQL append strings - mysql

how to insert a string from a particular position in another string to a column in database.Like i have column named Name in table world.Name column has a value Test.How to insert in the string name from 2nd postion that is from after e in test.Like test should become tenewst.
Database name :World
Table Name :Name
A Value in Name Table: Test
Desired output: Te-New-st-
(That is adding string "New" afer 2nd position in "Test" string.)

For SQL Server
--Original String
DECLARE #orgString varchar(50) = 'This is some test string'
--Search String
DECLARE #searchString varchar(50) = 'te'
--String to insert into the original string
DECLARE #insertString varchar(50) = 'NEW'
SELECT
CONCAT(SUBSTRING(#orgString,1,CHARINDEX(#searchString,#orgString)+1),
#insertString,
SUBSTRING(#orgString,CHARINDEX(#searchString,#orgString)+2,LEN(#orgString)))
AS String
To run something like this against data in your table, replace the original string variable with your column name
--Search String
DECLARE #searchString varchar(50) = 'te'
--String to insert into the original string
DECLARE #insertString varchar(50) = 'NEW'
SELECT CONCAT(SUBSTRING(Name,1,CHARINDEX(#searchString,Name)+1),
#insertString,
SUBSTRING(Name,CHARINDEX(#searchString,Name)+2,LEN(Name)))
AS String
FROM Table_1
If it is ALWAYS going to be between the 2nd and 3rd position, you could simplify it a little to this.
--String to insert into the original string
DECLARE #insertString varchar(50) = 'NEW'
SELECT CONCAT(SUBSTRING(Name,1,2),
#insertString,
SUBSTRING(Name,3,LEN(Name)))
AS String
FROM Table_1
Check out this for string function references, String Functions

Related

MySQL; the function value doesn't appear in resulted table

I created a table with three fields and applied a created function to automatic concat two fields of the same record and the result appears in the third field of the table at the same record.
While the problem is whenever I do insert statement the result of the function appears as error but not on the table!!! the following is the code:
create table Tab (
stuId varchar (1),
stuName varchar (10)
recordCon varchar (20),
primary key (stuId));
Auto concat function for one record by input id:
DELIMITER //
CREATE FUNCTION AutoCon (id varchar (1)) RETURNS int DETERMINISTIC
BEGIN
DECLARE name varchar(10);
DECLARE Con varchar(20);
select stuName from Tab where stuId = id into name;
Select concat(id, name) into con;
RETURN con;
END
//
DELIMITER ;
insert into Tab values ('1a', 'Rami', AutoCon('1a'))
the result
a1 Rami null
FUNCTION AutoCon (id varchar (1)), but you pass 2 chars as the parameter - AutoCon('1a')
Something wrong there ...

Get String between two strings - SQL Server

I got a function that returns string between two strings:
CREATE FUNCTION dbo.udf_GetStringBetween2Chars (#String VARCHAR(50), #FirstSpecialChar VARCHAR(50), #LastSpecialChar VARCHAR(50))
RETURNS VARCHAR(50)
AS
BEGIN
DECLARE #FirstIndexOfChar INT,
#LastIndexOfChar INT,
#LengthOfStringBetweenChars INT
SET #FirstIndexOfChar = CHARINDEX(#FirstSpecialChar,#String,0)
SET #LastIndexOfChar = CHARINDEX(#LastSpecialChar,#String,#FirstIndexOfChar+1)
SET #LengthOfStringBetweenChars = #LastIndexOfChar - #FirstIndexOfChar -1
SET #String = SUBSTRING(#String,#FirstIndexOfChar+1,#LengthOfStringBetweenChars)
RETURN #String
END
However, when I try to get string between POINTDESCRIPTION and DATAPOINT, I get error:
SET ANSI_WARNINGS OFF
declare #table table
(string varchar(50))
insert into #table
select 'EVENT: ID Order Reassignment (Individual Job Specific Update)|||LOCATION: Reassign.reassign()|||DATEPOINTDESCRIPTION: Only specific ID orders were reassigned from user fatis to user blake.|||DATAPOINT: blake' union all
select 'EVENT: ID Order Reassignment (Individual Job Specific Update)|||LOCATION: Reassign.reassign()|||DATAPOINTDESCRIPTION: Only specific ID orders were reassigned from user ilevic to user manic2.|||DATAPOINT: manic2' union all
select 'EVENT: ID Order Reassignment (Individual Job Specific Update)|||LOCATION: Reassign.reassign()|||DATAPOINTDESCRIPTION: Only specific ID orders were reassigned from user links to user sepir.|||DATAPOINT: sepir'
select dbo.udf_GetStringBetween2Chars (Tab.string,'POINTDESCRIPTION: ','|||DATAPOINT')
FROM #table Tab
Msg 537, Level 16, State 2, Line 10
Invalid length parameter passed to the LEFT or SUBSTRING function.
Does anyone see why this would happen?
If anyone finds it useful, here is final function to return string between 2 strings:
CREATE FUNCTION dbo.udf_GetStringBetween2Chars (#String VARCHAR(500), #FirstSpecialChar VARCHAR(500), #LastSpecialChar VARCHAR(500))
RETURNS VARCHAR(500)
AS
BEGIN
DECLARE #FirstIndexOfChar INT,
#LastIndexOfChar INT,
#LengthOfStringBetweenChars INT
SET #FirstIndexOfChar = CHARINDEX(#FirstSpecialChar,#String,0)
SET #LastIndexOfChar = CHARINDEX(#LastSpecialChar,#String,#FirstIndexOfChar+1)
SET #LengthOfStringBetweenChars = #LastIndexOfChar - #FirstIndexOfChar -1
SET #String = SUBSTRING(#String,#FirstIndexOfChar+LEN(#FirstSpecialChar),#LengthOfStringBetweenChars)
RETURN #String
END
GO
And to call it:
select dbo.udf_GetStringBetween2Chars (tab.someString,'POINTDESCRIPTION: ','|||DATAPOINT')
FROM yourTable tab

mysql different row updates depending on a variable (stored procedure)

CREATE PROCEDURE update_table(
IN choice INT(4),
IN id VARCHAR(50),
IN string VARCHAR(50)
)
BEGIN
UPDATE salesman
set salesman_name = IF(choice = 1, string, salesman_name)
where salesman_id = id
UPDATE salesman
set date = IF(choice = 2, string, date)
where salesman_id = id
END
if choiceis 1, change salesman_name as string
if choice is 2, change date as string
can you explain me what i'm doing wrong?
it works fine with a single update, my guess is there is another way to implement if but i couldn't.
if choice = 1 then
update salesman set salesman_name = string where salesman_id = id
...i tried this version too but still, not working.
DELIMITER //
CREATE PROCEDURE update_table(
IN choice INT(4),
IN id VARCHAR(50),
IN string VARCHAR(50)
)
BEGIN
UPDATE salesman set salesman_name = IF(choice = 1, string, salesman_name) where salesman_id = id;
UPDATE salesman set date = IF(choice = 2, string, date) where salesman_id = id;
END //
DELIMITER ;
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER' at line 1
also says this:
ERROR: Unknown Punctuation String # 11 (last line)
When a stored procedure has more than one statement, they need to be terminated with ;
To do that, you need to tempoararily change the delimiter so you can end the procedure. Here's a SO answer with an example of how to do that: MySQL create stored procedure syntax with delimiter

How to insert single row in parent table and multiple rows in child table using single stored procedure SQL Server 2008?

I have two tables:
The first one is Requisitions (parent table):
RequisitionId int // primary key
RequisitionNumber varchar(20)
RequisitionBy varchar(100)
Remarks varchar(300)
ApprovedStatus varchar(20)
Other one is RequisitionDetails (child table):
RequisitionDetailId int // primary key
RequisitionId int // foreign key ("Requisitions" table)
ProductId int
UnitConversionId int
Quantity decimal(18, 2)
Now I want to insert one row into the Requisitions table and mutiple rows in RequisitionDetails table using a single stored procedure.
The stored procedure should contain ROLLBACK command if there is any problem in the transaction. I need help writing this stored procedure.
I've created stored procedure to insert one row in "Requisitions" table and I have the RequisitionId of the inserted row. Now using this RequisitionId how could I insert multiple row for RequisitionDetails table?
Here is the stored procedure. I need to extend it:
CREATE PROCEDURE dbo.InsertRequisition
(
#RequisitionNumber varchar(20) = NULL,
#RequisitionBy varchar(100) = NULL,
#Remarks varchar(300) = NULL,
#ApprovedStatus varchar(20) = NULL
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #requisitionId INT;
INSERT INTO [Requisitions]
(
[RequisitionNumber],
[RequisitionBy],
[Remarks],
[ApprovedStatus]
)
VALUES
(
#RequisitionNumber,
#RequisitionBy,
#Remarks,
#ApprovedStatus
)
SET #requisitionId = SCOPE_IDENTITY();
END
If i understood the problem correctly, below code should be able solve your problem.
Step 1 : Create Type in Database
CREATE TYPE AnyNameTableType AS TABLE
(ColumnName1 INT, ColumnName2 VARCHAR(50))
Step 2 : Create/Modify your Stored Procedure to accept table type
CREATE PROCEDURE My_TestProc
(#tvpVariableName AnyNameTableType READONLY)
AS
BEGIN
SELECT * FROM #tvpVariableName;
--You can use this variable as table anywhere you want
--Select/Insert/Update from this table and update your RequisitionDetails
--table.
END;
Step 3 : Write your c# code to pass this variable.
DataTable table = new DataTable(); //Define your datatable simillar to TableType declared in SQL
table.Columns.Add("ColumnName1"); //Same Column Name you should use as of TableTYpe
table.Columns.Add("ColumnName2");
DataRow row = table.NewRow();
row["ColumnName1"] = 1; //Fill you datatable with data you want
row["ColumnName2"] = "Pratik";
table.Rows.Add(row);
table.AcceptChanges();
SqlConnection connection = new SqlConnection("data source=yoursource;database=test;uid=sa;pwd=yourpwd");
SqlCommand selectCommand = new SqlCommand("My_TestProc", connection);
selectCommand.CommandType = CommandType.StoredProcedure;
SqlParameter tvpParam = selectCommand.Parameters.AddWithValue("#tvpVariableName", table);//Parameter Name
tvpParam.SqlDbType = SqlDbType.Structured; // Very Important Not to miss
connection.Open(); //You can add multiple parameters also.
grid.DataSource = selectCommand.ExecuteReader();
grid.DataBind();
connection.Close();
After this steps if you have any confusion let me know.

Function SQL Server 2008

I created the following function yesterday, and now I am facing an error:
Invalid length parameter passed to the left or substring function
Could you guys have a look at my function?I really appreciate it.
Create function nowFunctionNewadd
(#fladd varchar(255))
returns #tbl table(addr varchar(100), city varchar(100),
state varchar(100), Zip varchar(5))
as
begin
declare #str varchar(100)
,#i int
,#j int
,#str2 varchar(100)
,#address varchar(100)
,#city varchar(100)
,#lastcomma int
,#lastPart varchar(100)
,#zipstart int
,#zip varchar(5) = ''
select #str=rtrim(ltrim(#fladd))
set #i = charindex(',', #str)
set #str2=rtrim(ltrim(substring(#str, #i+1, 999)))
set #j=CHARINDEX(',',#str2)
set #lastcomma = len(#str) - charindex(',', reverse(#str)+',')
set #lastPart = substring(#str, #lastcomma+2, 100)
set #address = REPLACE(rtrim(ltrim(substring(#str,1,#i-1))),',','')
set #zipstart = patindex('%[0-9]%', #lastpart)
set #city=LTRIM(RTRIM(substring(#str, #i+1, #j-1)))
If #zipstart > 0
select #zip = substring(#lastpart, #zipstart, 5),
#lastPart = rtrim(substring(#lastpart, 1, #zipstart-1))
insert into #tbl(addr, city, state, Zip)
values(#address, #city, #lastpart, #zip)
return
end
The problem that I can see with your function starts with this line:
set #j=CHARINDEX(',',#str2)
And then I am guessing that the error is being thrown by this line:
set #city=LTRIM(RTRIM(substring(#str, #i+1, #j-1)))
Your function is working under the assumption that you will have more than one comma present in the string value that you are passing. But if you don't have more than one comma the value for #j will be zero and then you are trying to use a -1 as the length of the city and this will fail throwing the error you are getting.
I created a SQL Fiddle with a demo to work with. Using the address '1234 S.Alameda way,LA,CA12345' your function will work.
But if you change the value to '1234 S.Alameda way,LACA12345' it will fail
See SQL Fiddle Demo
Do you know what the format is going to be for all of the values that you need to pass into the function? If this format is going to change from 1 to 2 or even 3 commas I think you need to rethink how this function is written because it will not work as expected.