Select # before values - sql

I want to select name in email
Example:
sample#gmail.com
From that, I want to select 'sample' only.

This is for MS SQL Server. You can easily replicate this if you use any other RDBMS
declare #email varchar(100)
set #email='sample#gmail.com'
select substring(#email,1,charindex('#',#email)-1)

Try this
declare #email nvarchar(200) = 'sample#gmail.com'
select left(#email,charindex('#',#email,0)-1)

Related

How do i convert variable name to string name?

Assume I have the following SQL snippet in SQL Server 2012:
DECLARE #fname varchar(20), #strVarName varchar(50)
SET #fname = 'cronus'
SET #strVarName = COVERT_VARIABLE_TO_STRING_NAME ( #fname)
--this should return '#fname'. this is not a value conversion this is converting a variable name to a string name
SELECT #strVarName
How do I do this?
SQL Server does not support reflection. You may be able to retrieve column or table names from its catalog views but with variables you're out of luck. Maybe you'll find another way to solve this issue with dynamic SQL.
Use dynamic sql query
DECLARE #fname varchar(20), #sql varchar(MAX)
SET #fname = 'cronus'
SET #sql = 'SELECT ' + #fname
EXEC (#sql)
There are following Character data types used to store character strings:
char,
varchar,
nvarchar,
text,
If u already used variable as String then why need to convert as a string
DECLARE #fname varchar(20), #strVarName varchar(50)
SET #fname = 'cronus'
SET #strVarName = #fname
SELECT #strVarName
if needed use CAST and CONVERT function
This is such a bizarre question, sounds like something I'd try to do.
Hmm, SQL is not supposed to do this but I guess, it doesn't mean you can't make it.
I think you would effectively have to write your own process to pull this off, something along the lines of:
Create dbo.sProcInserts stored procedure to insert values into a table:
Takes VariableName, Value and possibly table name to insert into as parameters
Create dbo.sProcExec stored procedure to execute stored procedure:
Before execute, read stored procedure into a variable
Find all variables that are SET (i.e. they have a SET #Var = OR SELECT #Var =)
After each variable set, add to your string a line that calls dbo.sProcInserts with the name of the variable and a select #Variable
Execute your newly written stored procedure
That way you don't have to actually make any modifications to your sProcs and it should catch the flow of variables and their changes through your procedure
However the requirement itself is a bit strange for me, but here is a way that could be a good start point for you:
declare #var1 int
Set #var1= 1
--some code here
declare #var2 nvarchar(max)
set #var2 = 10
--some other code here
declare #var3 bit
print ##VERSION
print 'this is fake #value inside a string'
--$ This is a Hint to help me find the Query that should parsed
declare #sql varbinary(max)
select #sql=sql_handle
from sys.sysprocesses
where spid=56
declare #q nvarchar(max)
select #q= substring(text,1,charindex('$',text)-3) from sys.dm_exec_sql_text(#sql)
Select distinct rtrim(ltrim(substring(Name,1,charindex(' ',Name)))) as Name from(
Select substring(replace(Name,'=',' '),8, Len(Name)) as Name from dbo.SplitString(#q,'declare ')
) as K
where Name like '#[^#]%'
By running the above query you will get the variables name.
Output:
#var1
#var2
#var3
You can find the source code for SplitString function Here
Note: If you are using SQL Server 2016 and your database's compatibility level is equal or greater than 130, you can also use SPLIT_STRING introduced by Microsoft it self. Learn more Here

Send Email to each recipient stored into a table

I'm trying to send an email using the sql server email option, I already can send an email, but now I'm trying to send that email to dynamic recipients, for example... I have the following table:
ID | Email
..1| example#example.com
..2| example2#example.com
With my code I need to do the following thing:
#recipients = 'example#example.com; example2#example.com;'
What I want to do is to select that emails from a table, so if I edit one email I dont have to change anything about my code, just update the information from my table.
I'm thinking maybe do it by using a var, something like:
Declare #emails nvarchar(max)
set #email = query
then do something like a foreach (foreach email in #emails) or something like that (in T-SQL of course...)
Is this possible? Or what another solution can I try?
Recipients has the option to add more than one email in the same line, so maybe the easier way to solve your problem is select all the emails and then join them separated with a ;. If you thing that this is a good option you should try this code:
Declare #Emails nvarchar(MAX)
Select #Emails = coalesce(#Emails + ';', '') + Email from yourTable
//Your output should be: example#example.com;example2#example.com
Then all you need to do this:
#recipients = #Emails
You should use a cursor for that
DECLARE #email nvarchar(max)
set #email = ''
DECLARE #cursorName CURSOR FOR
SELECT emailColumn FROM tableName
OPEN #cursorName
Then you use a loop to concatenate each email
FETCH NEXT FROM #cursorName INTO #email
WHILE ##FETCH_STATUS = 0
BEGIN
set #email = #email+#cursorName+'; '
END
You need to concatenate the strings in the column, so something like this should work:
CREATE TABLE dbo.exampleTable (
id int,
email varchar(200)
)
INSERT INTO dbo.exampleTable VALUES (1,'a#a'),(2,'b#b')
SELECT stuff( (SELECT ';'+email
FROM dbo.exampleTable
FOR XML PATH(''), TYPE).value('.', 'varchar(max)')
,1,1,'')
There are also some other ways to do it: https://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/
The result of the query you build or use can be used to set your #email variable.

declare variables in sql 2005

In my script i have few select statements and update statements, as an example
SELECT * from TABLE1
WHERE userID= 'US001'
UPDATE TABLE2
SET value= 'months'
WHERE userID='US001'
statements going so on, so in this i have to copy and paste userID to every statement.
i want to declare a variable and assign to userID to refer it, so i don't need to add userID number to every query and i need to execute
i have tried this
Delcare #theID userID
SET userID ='us001'
but didn't work it out
please let me know..
thanks
You'll need to declare the type, and assign it. In Sql Server, variables are prefixed with #, like so:
DECLARE #theID NVARCHAR(20);
SET #theID ='us001';
UPDATE TABLE2 SET value= 'months' WHERE userID=#theID;
DECLARE #theID varchar(10);
SET #theID = 'us001';
In your statement you are declaring your variable as userID, which is not a valid data type.
In addition to the previous answers, in SQL Server 2008 and higher you can also declare and set the variable in a single line.
DECLARE #UserID NVARCHAR(20) = 'us001';
This is what works for me under SQL2005 in a stored procedure:
DECLARE #name varchar(100)
SELECT #name = 'Robin'
// and this should be do the update
SET userID = #name
// or in you query it should be
WHERE userID = #name

How to select only the characters appearing before a specific symbol in a SQL Select statement

I have strings in a database like this:
firstname.lastname#email.com/IMCLientName
And I only need the characters that appear before the # symbol.
I am trying to find a simple way to do this in SQL.
DECLARE #email VARCHAR(100)
SET #email = 'firstname.lastname#email.com/IMCLientName'
SELECT SUBSTRING(#email,0, CHARINDEX('#',#email))
Building on Ian Nelson's example we could add a quick check so we return the initial value if we don't find our index.
DECLARE #email VARCHAR(100)
SET #email = 'firstname.lastname.email.com/IMCLientName'
SELECT CASE WHEN CHARINDEX('#',#email) > 0
THEN SUBSTRING(#email,0, CHARINDEX('#',#email))
ELSE #email
END AS email
This would return 'firstname.lastname.email.com/IMCLientName'. If you used 'firstname.lastname#email.com/IMCLientName' then you would receive 'firstname.lastname' as a result.

TSQL Statement IN

I am having a small problem with the IN SQL statement. I was just wondering if anyone could help me?
#Ids = "1,2,3,4,5"
SELECT * FROM Nav WHERE CONVERT(VARCHAR,NavigationID) IN (CONVERT(VARCHAR,#Ids))
This is coming back with the error below, I am sure this is pretty simple!
Conversion failed when converting the varchar value '1,' to data type int.
The SQL IN clause does not accept a single variable to represent a list of values -- no database does, without using dynamic SQL. Otherwise, you could use a Table Valued Function (SQL Server 2000+) to pull the values out of the list & return them as a table that you can join against.
Dynamic SQL example:
EXEC('SELECT *
FROM Nav
WHERE NavigationID IN ('+ #Ids +')')
I recommend reading The curse and blessings of dynamic SQL before using dynamic SQL on SQL Server.
Jason:
First create a function like this
Create FUNCTION [dbo].[ftDelimitedAsTable](#dlm char, #string varchar(8000))
RETURNS
--------------------------------------------------------------------------*/
/*------------------------------------------------------------------------
declare #dlm char, #string varchar(1000)
set #dlm=','; set #string='t1,t2,t3';
-- tHIS FUNCION RETUNRS IN THE ASCENDING ORDER
-- 19TH Apr 06
------------------------------------------------------------------------*/
--declare
#table_var TABLE
(id int identity(1,1),
r varchar(1000)
)
AS
BEGIN
declare #n int,#i int
set #n=dbo.fnCountChars(#dlm,#string)+1
SET #I =1
while #I <= #N
begin
insert #table_var
select dbo.fsDelimitedString(#dlm,#string,#i)
set #I= #I+1
end
if #n =1 insert #TABLE_VAR VALUES(#STRING)
delete from #table_var where r=''
return
END
And then
set quoted_identifier off
declare #ids varchar(max)
select #Ids = "1,2,3,4,5"
declare #nav table ( navigationid int identity(1,1),theother bigint)
insert #nav(theother) select 10 union select 11 union select 15
SELECT * FROM #Nav WHERE CONVERT(VARCHAR,NavigationID) IN (select id from dbo.ftDelimitedAsTable(',',#Ids))
select * from dbo.ftDelimitedAsTable(',',#Ids)
What you're doing is not possible with the SQL IN statement. You cannot pass a string to it and expect that string to be parsed. IN is for specific, hard-coded values.
There are two ways to do what you want to do here.
One is to create a 'dynamic sql' query and execute it, after substituting in your IN list.
DECLARE #query varchar(max);
SET #query = 'SELECT * FROM Nav WHERE CONVERT(VARCHAR,NavigationID) IN (' + #Ids + ')'
exec (#query)
This can have performance impacts and other complications. Generally I'd try to avoid it.
The other method is to use a User Defined Function (UDF) to split the string into its component parts and then query against that.
There's a post detailing how to create that function here
Once the function exists, it's trivial to join onto it
SELECT * FROM Nav
CROSS APPLY dbo.StringSplit(#Ids) a
WHERE a.s = CONVERT(varchar, Nav.NavigationId)
NB- the 'a.s' field reference is based on the linked function, which stores the split value in a column named 's'. This may differ based on the implementation of your string split function
This is nice because it uses a set based approach to the query rather than an IN subquery, but a CROSS JOIN may be a little complex for the moment, so if you want to maintain the IN syntax then the following should work:
SELECT * FROM Nav
WHERE Nav.NavigationId IN
(SELECT CONVERT(int, a.s) AS Value
FROM dbo.StringSplit(#Ids) a