I have a TELEPHONE_NUMBER as a varchar like this:
Value : "1112223344"
And I need to add "-" to the value like this:
111-222-33-44
So how can I add - to my telephone number value in my SQL Server stored procedure?
CREATE PROCEDURE SP_TELEPHONE_NUMBER
(#TELEPHONE_NUMBER VARCHAR(4000))
AS
BEGIN
INSERT INTO DOSYA_ARSIV(TELEPHONE_NUMBER)
VALUES(#TELEPHONE_NUMBER)
END
Just an alternative:
select SUBSTRING('1112223344',1,3)+'-'+
SUBSTRING('1112223344',4,3)+'-'+
SUBSTRING('1112223344',7,2)+'-'+
SUBSTRING('1112223344',9,2)
In your case:
CREATE PROCEDURE SP_TELEPHONE_NUMBER
(#TELEPHONE_NUMBER VARCHAR(4000))
AS
BEGIN
INSERT INTO DOSYA_ARSIV(TELEPHONE_NUMBER)
VALUES
(
SUBSTRING(#TELEPHONE_NUMBER,1,3)+'-'+
SUBSTRING(#TELEPHONE_NUMBER,4,3)+'-'+
SUBSTRING(#TELEPHONE_NUMBER,7,2)+'-'+
SUBSTRING(#TELEPHONE_NUMBER,9,2)
)
END
As noobob has mentioned in his comment, you may have this as an INT type (INT,BIGINT or something similar) and just handle the way it is displayed in the front end. For instance in C# you would have it as:
TELEPHONE_NUMBER.ToString("###-###-##-##");
Another comment would be that defining the expected argument as VARCHAR(4000) is way too much. Though it might not be very bad, it is a good point to define arguments or variables as close to expected input as you can. In your case i would say that something like VARCHAR(30) would be enough.
Use STUFF function in the MS SQL server
SET #TELEPHONE_NUMBER=STUFF(STUFF(STUFF(#TELEPHONE_NUMBER,4,0,'-'),8,0,'-'),11,0,'-')
Related
I am trying to input a tuple of room here is my code for insert
create proc spInsertToRoom
#room_name varchar(50),
#room_status varchar(50)='Available',
#room_rate float
AS
BEGIN
INSERT INTO tblRoom(room_name,room_status,room_rate)
SELECT #room_name,#room_status,#room_rate
END
I want the status to be automaticly available. Then when I input a value
it just keeps on saying
exec [spInsertToRoom]'A102',3500
Procedure or function 'spInsertToRoom' expects parameter '#room_rate',
which was not supplied.
But when I try this
exec [spInsertToRoom]'A103',#room_rate=4000
It worked!
I'm Just wondering why is it needed to to input the #room_rate=4000 whereas what I saw on youtube is a person just input a variable just like my former code?
In this case you need to name the parameters in your call. With your code what is happening is it will implicitly convert 3500 to varchar(50) and then not find a value for room_rate.
exec [spInsertToRoom] #room_name = 'A102', #room_rate = 3500
I would make a couple recommendations. First is not to use float when you want the number to be precise. Float is an approximate datatype. Something like NUMERIC(9, 2) would be a better choice.
My second recommendation is to drop the prefix from your names. It is just noise when looking for a procedure name and it isn't likely to get confused with something else. If that were my system the name for this proc would be Room_Insert. That way the procs will sort by the object they are dealing with and the verb is at the end. Room_Update, Room_Delete etc will all be next to other in the list of procedures when sorted alphabetically (like in SSMS).
I have a varchar variable been defined like this.
declare #IDs varchar(50)
set #IDs ='111,123,567,'
Now I need to extract the last value in the list always 567.
The values in #IDs can be like this also
set #IDs ='56,'
In this case we need extract only the value 56.
How can we do it?
i think you will find this user defined function to split the string helpful:
http://www.codeproject.com/Articles/7938/SQL-User-Defined-Function-to-Parse-a-Delimited-Str
You can use the string splitter found here: http://www.sqlservercentral.com/articles/Tally+Table/72993/
It is very fast, you can call it like so:
SELECT *
FROM dbo.DelimitedSplit8K(#IDs,',')
This will return you a result set of all the values in the string.
Is there a way to call a User defined function without using "dbo." before the function name and parameters?
Using:
SELECT USERFUNCTION(PARAM1, PARAM2, PARAM3, PARAMN)
instead of:
SELECT dbo.USERFUNCTION(PARAM1, PARAM2, PARAM3, PARAMN)
This isn't possible for the SELECT syntax. BOL States: "Scalar-valued functions must be invoked by using at least the two-part name of the function"
This syntax works however.
CREATE FUNCTION USERFUNCTION
(#p INT)
RETURNS INT
AS
BEGIN
RETURN (2)
END
GO
DECLARE #rc INT
EXEC #rc = USERFUNCTION 1
SELECT #rc
It is best practice to always explicitly schema qualify objects you are referencing anyway though to avoid some overhead for resolving the schema (and avoid the possibility that the schema cannot be resolved implicitly or is resolved in a way that is undesired)
There are various ways to do this, if we take it that you have a negative reaction to seeing "dbo.".
In SQL Server 2000, there is a way to turn UDFs into system functions by toggling a bit. This "feature" has been removed from SQL Server 2005 onwards, so I won't go into detail unless you really are still using 2000.
You can use OPENQUERY with PROC syntax similar to what Martin has shown.
You can turn the Scalar function into a Table Valued Function, either by rewriting it, or by wrapping it in a TVF. The syntax changes however, so
select dbo.udf(a,b) from c
--becomes
select d
from c
cross apply tvf(a,b) e(d) -- look, no "dbo"!
But none of the above looks simpler than just tacking a simple "dbo." prefix to the function name, so why would you do it?
Yes Possible,
Actually when function returning scalar value you must call with schema name like dbo.yourfunction , If you don't want to call function without schema name you should create function as follows.
Sample Code:
CREATE FUNCTION [dbo].[FN_MAPCOUNT]
(
#countValue int
)
RETURNS #TEMPTABLE Table(cntValue int)
as
begin
DECLARE #countValueint
#countValue= select count(*) from mappings;
INSERT #TEMPTABLE (cntValue) VALUES (#countValue)
RETURN
end
Go
select * from FN_MAPCOUNT(1);
The reason is you are returning the value as table .
Is there a way to do something like this without converting the sql to a string and calling exec
DECLARE #source_database varvhar(200)
SELECT #source_database = 'wibble'
SELECT * FROM SELECT #source_database.dbo.mytable
No. I'm afraid not.
It is necessary to use dynamic sql in order to use a variable for either a database or column name.
Only for stored procs without using linked server or dynamic SQL
DECLARE #myProc varchar(200)
SELECT #myProc = 'wibble.dbo.foobar'
EXEC #myProc
There is another (not necessarily pretty) alternative:
IF (#source_database = 'wibble')
USE wibble;
ELSE IF (#source_database = 'wibble2')
USE wibble2;
ELSE
RAISERROR(....)
SELECT * FROM dbo.myTable
If you have any real number of databases, this may be tiresome. But it's an option nonetheless.
I am trying to issue a SQL update statement with nHibernate (2.0.1GA) like this:
sqlstring = string.Format("set nocount on;update myusers set geo=geography::Point({0}, {1}, 4326) where userid={2};", mlat, mlong, userid);
_session.CreateSQLQuery(sqlstring).ExecuteUpdate();
However I receive the following error: 'geography#p0' is not a recognized built-in function name.
I thought CreateSQLQuery would just pass the SQL I gave it and execute it...guess not. Any ideas on how I can do that within the context of nHibernate?
I'm pretty sure I can tell you what is happening, but I don't know if there is a fix for it.
I think the problem is that the ':' character is used by NHibernate to create a named parameter. Your expression is getting changed to:
set nocount on;update myusers set geo=geography#p0({0}, {1}, 4326) where userid={2};
And #p0 is going to be a SQL variable. Unfortunately I can't find any documentation for escaping colons so they are not treated as a named parameter.
If an escape character exists (my quick skim of the NHibernate source didn't find one; Named parameters are handled in NHibernate.Engine.Query.ParameterParser if you want to spend a little more time searching), then you could use that.
Other solutions:
Add an escape character to the source. You can then use a modified version of NHibernate. If you do this, you should submit your patch to the team so it can be included in the real thing and you don't have to maintain a modified version of the source (no fun).
Create a user defined function in your DB that returns a geography::Point, then call your function instead of the standard SQL function. This seems like the quickest/easiest way to get up and running, but also feels a bit like a band-aid.
See if there is something in NHibernate Spatial that will let you programmatically add the geography::Point() [or edit the code for that project to add one and submit the patch to that team].
"{whatever} is not a recognized built-in function name" is a SQL Server error message, not sure what Hibernate is doing there but SQL Server is the one complaining about it.
There is an implicit conversion from varchar to Point.
Use NHibernate to set the geographic parameters to their string representation
Define a SQL query template with named paramter loc:
const string Query = #"SELECT {location.*}
FROM {location}
WHERE {location}.STDistance(:loc) is not null
ORDER BY {location}.STDistance(:loc)";
Set the parameter to a string representation of Point:
return session
.CreateSQLQuery(Query)
.AddEntity("location", typeof (Location))
.SetString("loc", "Point (53.39006999999999 -3.0084007)")
.SetMaxResults(1)
.UniqueResult<Location>();
This is for a Select. but I see no reason why it wouldn't work for an Insert or Update.
Following on #Chris's answer, here is a copy and paste solution:
CREATE FUNCTION GetPoint
(
#lat float,
#lng float,
#srid int
)
RETURNS geography
AS
BEGIN
declare #point geography = geography::Point(#lat, #lng, #srid);
RETURN #point
END
GO
The you do
dbo.GetPoint(#Latitude, #Longitude, 4326)
instead of
geography::Point(#Latitude, #Longitude, 4326);
And NH is happy