Transact SQL :: Can Add 1 To Charindex Function But Can't Minus 1
Aug 25, 2015
The charindex can run this
LEFT([Description], CHARINDEX('(', [Description]) + 1) as NewDesc,
But I can't run
LEFT([Description], CHARINDEX('(', [Description]) - 1) as NewDesc,
View 5 Replies
ADVERTISEMENT
Mar 22, 2006
I have two tables CarType & Cars. Table CarType has a column CarTypeId which is the primary key (int, identity). Table Cars includes a column CarTypeId (int) which is a foreign key into the CarType table.Now I am trying to build a list of all those CarTypeId entries (from the CarType table) for which there are no Cars (i.e. there is no corresponding entry in the Cars table).I read that there is an SQL "MINUS" keyword that you can use like this:
SELECT CarTypeId FROM CarTypeMINUSSELECT CarTypeId FROM Cars..So if CarType contains records with the keys {1, 2, 3, 4, 5} and Cars contains records with the foreign keys {2, 4} (using set notation), your result should be the set {1, 3, 5}. (Note: I have tried alternate versions of this where I selected the DISTINCT CarTypeId entries from Cars, and where I sorted them; results same in both cases).I tried it in SQL Server 2005 Express. The result is just {1, 2, 3, 4, 5}.
Is the MINUS capability supported by SQL Server? I know that there are all sorts of different SQL dialects & implementations and that SQL has evolved & transmutated over the years; perhaps they opted to leave this out of SQL Server..
Here's a reference to the website where I initially found out about MINUS: [URL] ....
View 19 Replies
View Related
Jul 10, 2015
What is the best way to convert 3/1/1/12/0 into xxx-xx-xx-xx-xx format by appending zeros if required. final result should be
300/10/10/12/00.
View 9 Replies
View Related
Jul 20, 2005
My code prints out 0 for the value of charindex ( 'Hello.', '.' ).Did I miss something? I think it should print out 6!
View 1 Replies
View Related
May 23, 2007
Hello to all,
I hope that somebody can help me.
I have written a sql query to search Partner. I have a wtcomValidRelationships Table. There are two Fields (IDMember(type: Int) and RelationshipIDs(type: varchar(1000)) in this table.
Example: 3418 has 3422 RelationshipID and 3422 has 4088 RelationshipID, if i want to check if there is a relationship between 3418 and 4088.
declare @IDM int;
declare @IDO char(100);
set @IDM = 3418;
set @IDO = '4088';
select B.IDMember
from wtcomValidRelationships as A, wtcomValidRelationships as B
where A.IDMember = @IDM and charindex(cast(B.IDMember as char(100)),A.RelationshipIDS) > 0
and charindex(@IDO,B.RelationshipIDs) > 0
Using this query i get nothing.
I try to use constant in charindex and i get result.
declare @IDM int;
declare @IDO char(100);
set @IDM = 3418;
set @IDO = '4088';
select B.IDMember
from wtcomValidRelationships as A, wtcomValidRelationships as B
where A.IDMember = @IDM and charindex('3422',A.RelationshipIDS) > 0
and charindex('4088',B.RelationshipIDs) > 0
So i think that charindex doesn't work with variable. But I must use variable. Can someone help me? What should i do ?
Thanks
Best Regards
Pinsha
View 1 Replies
View Related
Mar 30, 2015
SELECT LEFT(InstanceName,CHARINDEX(' ',InstanceName)-1)
FROM ServerDB
Returns the following error.
Invalid length parameter passed to the SUBSTRING function.
View 2 Replies
View Related
Jul 20, 2015
I’ve got an issue with extracting specific data from one field using charindex. Here’s an example of the dataset:
Cl_nr Var_data
20059942 ?;;300134BL10;?;;;;;;
20059958 ;2698;020225PU20;?;;;;;;
20059975 ;;100777ST20;?;;;;;;
20059976 ;;;;;;;;;
11001980 ;;051168PU20;?;;;;;;1001980
20034832 ;;060253BO10;?;;;;;;
20055246 ;;1108731;?;?;;;;;
20043656 ;;1022509;?;;;;;;
20059366 ;;1181750;31-12-2015;2;;;;;
20052712 ;;230626NO10;?;;;;;;
Goal is to get the data after the 2<sup>nd</sup> ; until the next ; starts. Ideal would be to catch everything between the 2<sup>nd</sup> ; en 3<sup>rd</sup> ; (number should be 10 characters).
If I try to select this data just using charindex it only goes until it finds the first ; (of course), what’s the best approach in this?
View 4 Replies
View Related
Aug 5, 2013
SQL Query. What i need is to be able to extract specific characters from data.
Eg name
1.2-KPIA1-App-00001 this is a name i require, but i also require the '1.2' and the 'KPIA1' to be displayed in new columns in the results
i.e. 1.2-KPIA1-App-00001 1.2 KPIA1
*I need this in part of a script as there is thousands of rows of data.
View 4 Replies
View Related
Oct 4, 2007
Hello All,
I need to determine that a piece of XML in a character field or variable is well-formed XML. I need to store this validation result (valid or not valid flag) in the table.
Does SQL provide some function for this? Is there any other way?
Thank you!
David
View 2 Replies
View Related
Mar 22, 2002
HI there,
Is there a function on transact SQL which test if a character belong to expression,I want to select from a table only the address that contain '@'.
Thanks in advance
Jalal
View 1 Replies
View Related
Nov 2, 2015
The input is like this : xxxxxxxx=yyyyy=key_id=12345xyxyx
I would like to use the right function and get 12345xyxyx alone. The function must search for the first '=' symbol from the right of the word and get the characters from the end till the '=' symbol.
View 2 Replies
View Related
Oct 14, 2005
Hi All,
Once again I find myself smacking my head into a wall (and it will probably be for naught). I'm trying to find a specific character in a string within a specific record. I've tried substring, but it's not quite getting me where I want to be. I even tried "nesting" the substring and got nowhere (but I could have had the syntax wrong when I nested it).
Here is a sample
Select substring(productimagefile, 20, 5)
from my table
What I need is something like this:
Select substring(findoneof(productimagefile, _r, 1), 1, 5)
from my table
Actually, on the start of the substring, I need it to be where it finds the _r, just not sure how to tell it that.
The replace function is the closest I've seen to what I need, but I don't want to replace it with anything, I just need to find it in the string.
So, if anyone has any ideas, I'd be grateful (and my head would stop hurting....)
Schimelcat
View 1 Replies
View Related
Jun 2, 2006
I currently have the fllowing Stored Procedure. When I pass the the Url of the web service in the parameters, I'm having a sp_OAMethor read response failed error.
I don't know how to pass the parameter as well as the name of the function in the Web Service I'm calling. Maybe I'm all wrong here with this code too?
Thanks for any help.
ALTER PROCEDURE [dbo].[pTAPServiceWeb]
@sUrl varchar(200),
@response varchar(8000) out
AS
DECLARE @obj int
DECLARE @hr int
DECLARE @status int
DECLARE @msg varchar(255)
EXEC @hr = sp_OACreate 'MSXML2.ServerXMLHttp', @obj OUT
IF @hr < 0
BEGIN
RAISERROR('sp_OACreate MSXML2.ServerXMLHttp failed', 16, 1)
RETURN
END
EXEC @hr = sp_OAMethod @obj, 'Open', NULL, 'GET', @sUrl, false
IF @hr < 0
BEGIN
SET @msg = 'sp_OAMethod Open failed'
GOTO err
END
EXEC @hr = sp_OAMethod @obj, 'send'
IF @hr < 0
BEGIN
SET @msg = 'sp_OAMethod Send failed'
GOTO err
END
EXEC @hr = sp_OAGetProperty @obj, 'status', @status OUT
IF @hr < 0
BEGIN
SET @msg = 'sp_OAMethod read status failed'
GOTO err
END
-- IF @status <> 200
-- BEGIN
-- SET @msg = 'sp_OAMethod http status ' + str(@status)
-- GOTO err
-- END
EXEC @hr = sp_OAGetProperty @obj, 'responseText', @response OUT
IF @hr < 0
BEGIN
SET @msg = 'sp_OAMethod read response failed'
GOTO err
END
EXEC @hr = sp_OADestroy @obj
RETURN
err:
EXEC @hr = sp_OADestroy @obj
RAISERROR(@msg, 16, 1)
RETURN
GO
View 3 Replies
View Related
May 3, 2006
Dear all,
I want to know difference between Metadata function and Transact-SQL. When to use metadata function and when Transact-SQL like
To know database exists in SQL Server we have two options
through Transact-SQL
if not exists(select * from sysdatabases where name = 'Testing')
through Metadata function
if db_id('Testing') is not null
When should I use Transact-SQL and when metadata function.
Thanks,
Ashok
View 1 Replies
View Related
Jun 23, 2015
I have a table with duration values for different machine states. I 'm trying have a sum of the duration value of each state ( the duration sum , was an earlier question).
declare
@tblDurations
TABLE
(StateName
nvarchar(30),Duration
nvarchar(30))
[code]...
I want the output to have sum of the duration ( from my function ), grouped by the state.So output should be :
Breaks 00:02:03:40
Meetings 00:00:01:50
Running 15:21:07:16
I think this can be done with windows functions, but how I don't know.
View 10 Replies
View Related
Oct 11, 2015
I want to create a subset of a geography table. My intention is to select only a few cities with a where and after that select a percent of village for each of the cities. My query look like this:
SELECT TOP 160 [CodMunicipio] ,[NombreMunicipio] ,[CodProv],[Provincia] ,[COMUNIDAD AUTÓNOMA]
,[Longitud ETRS89/REGCAN95],[Latitud ETRS89/REGCAN95]
,[XUTM ETRS89/REGCAN95],[YUTM ETRS89/REGCAN95],[Bandera]
--INTO [PracticasSCD].DBO.DIMGEOGRAFIA
FROM [SportFunDW].[dbo].[DimGeografia2] TABLESAMPLE (3 PERCENT)
[Code] ....
I have tried with tablesample but it doesn´t return what I expect because I have many villages from one city (for example 15 % of it) and only 2 % of other. How can I achieve my goal?
View 5 Replies
View Related
Aug 6, 2015
SSMS does not like mine! THis is the error that I receive:
Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
And this is my syntax:
Select
employeeID
,COUNT(case when rehirestatus IN (select rehirestatus from regionalemptable where rtrim(storename) = 'Location1') THEN userID ELSE 0 END) +
COUNT(case when rehirestatus IN (select rehirestatus from globalemptable where rtrim(storename) = 'Location1') Then userID ELSE 0 End)
FROM production
GROUP BY employeeID
ORDER BY employeeID
View 6 Replies
View Related
Jun 9, 2015
When I am doing the divide all values are showing Zero.
DECLARE @test_sample TABLE (ClientID VARCHAR(5), FiscalYear varchar(4), QtrNumerator int, QtrrDenominator int)
INSERT INTO @test_sample VALUES
('ABC','2014',0,100),
('ABC','2015', 10,40),
('CDE','2013',14,0),
('CDE','2012',20,50)
select QtrNumerator/nullIf(QtrrDenominator,0) as QTR from @test_sample
and also I want to show the QTR with %, for example, 66.57%
View 6 Replies
View Related
Sep 23, 2015
I have an SP that is working, it creates a Union between 3 tables then creates a single table - I am using Visual studio Grid Control to view this by a browser, its working. at the bottom of the SP is a line of code that calls a function, the function queries a View. When I run the SP, SQL returns the data from the Union plus the data from the select statement on the Function. This all works but I can't get the data returned by the function query onto a browser.
I am doing it this was as the parameters in my SP are also used when calling the function, works really well. Is GTotal a return value?
Here is my function:
USE [LOGONs]
GO
/****** Object: UserDefinedFunction [dbo].[FX_AnnaulBudget1] Script Date: 23/09/2015 12:27:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
[Code] ....
...and here is my SP:
USE [LOGONs]
GO
/****** Object: StoredProcedure [dbo].[USP_AnnualBudget] Script Date: 23/09/2015 12:57:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[USP_AnnualBudget]
[Code] .....
View 2 Replies
View Related
Jul 1, 2015
Update query to modify a Url in the text column with another url
Ex:
Col1 Col2
1 An unexpected event occurred
https://abc.def.com/default/_workitem/10325
3 This alert occurs when service jobs run on
https://abc.def.com/default/_workitem/10118
10 This alert fired to indicated that error with
https://abc.def.com/default/_workitem/10150
to
Col1 Col2
1 An unexpected event occurred
https://abc.def.com/default/_workitem/11111
3 This alert occurs when service jobs run on
https://abc.def.com/default/_workitem/11111
10 This alert fired to indicated that error with
https://abc.def.com/default/_workitem/11111
View 3 Replies
View Related
Apr 25, 2015
I have a really basic question. The following SQL query works for me:
Select EnterUserID, Enterdate
from tblCsEventReminders
where EnterDate >= Convert(datetime, '2015-04-01')
I am essentially trying to write a query to count the number of user logins after a certain date, so I need to count 'EnterUserID' but I am having problems getting the count() function to work.
View 3 Replies
View Related
Jan 18, 2005
If I was asked "How many days passed" the query is (below) and the answer is 33. But, then the curve ball is "can you subtract out the weekends?" and I said....well, I said I think so, but not sure how. So far, I have had no luck. Any advise?
SELECT
DATEDIFF ( dd , dbo.table_case.creation_time , dbo.table_close_case.close_date ) AS no_of_days,
dbo.table_case.id_number,
dbo.table_case.creation_time CreateTime,
dbo.table_close_case.close_date CloseDate
FROM
dbo.table_case,
dbo.table_close_case
WHERE
dbo.table_close_case.last_close2case=dbo.table_case.objid AND
dbo.table_case.id_number = '969382'
ORDER BY no_of_days ASC
View 2 Replies
View Related
Jun 2, 2007
Hello:
I need to change minus brackets () with - sign in SSRS. How i can do this?
Thanks
Amit
View 11 Replies
View Related
May 14, 2015
I've a scalar function which is killing my performance. I've been used the SQL profiler and also DMVs to catch execution information. I'd like to store the value received by this function and also the time that it happened, but I can't think in a way to do it.
View 5 Replies
View Related
Jul 1, 2015
I have a query that uses the PIVOT function and works fine in SQL 2012. I've been asked to move the query to a database that has the compatibility level set to 80(SQL 2000). I receive an "Incorrect syntax near" error when I try to excute the query on the SQL 2000 database. I would like to duplicate the exiting PIVOT functionality in SQL 2000.The existing query retrieves employee names and the order that the employee should be displayed from a table. The names will appear on the report according to the order that is retrieved from the database. Also, the users have requested that only 5 names appear on each row of the report. This is why the PIVOT function was needed. Below is an example of how the existing query works.
Table
CREATE TABLE [dbo].[EmpGuest](
[Guest_ID] [int] NOT NULL,
[Guest_Name] [varchar](80) NULL,
[Display_Order] [int] NULL
) ON [PRIMARY]
[code]....
View 4 Replies
View Related
Jun 16, 2015
SQL Sever 2012, I have a table where I store data related with a Log, the columns of the table are three, IDTable, DateLog and CountLog, the column CountLog is a cumulative value, each new rows can increment this value, my query will receive two parameters related with the Date, @dateFrom and @dateTo, with this information is necesary to get the diff between two months, for example:
CREATE TABLE MyTable
(
IDTable INT IDENTITY NOT NULL,
DateLog DATE NOT NULL,
CountLog INT NOT NULL
)
[code]....
In this case I need to apply a filter with the Dates:
@dateFrom ='2014-01-01',
@dateTo ='2014-04-28'
But according with this filter I need to limit the results only for this period between the date, but I need that the first month (January 2014) take the information of the max value from previous month even not included in the filter, in this case the results will be the next:
Id MonthYear Diff
1 Jan2014 5
2 Feb2014 3
3 March2014 0
4 April2014 5
With the results, for the first mont (January) is, according to the range of times, January is the lower limit,the last cumulative value of CountLog before the first month of the range was 2 (December 2013), the max value of the CountLog for this first month was 7, the diff is 7-2 equal to 5 , in the case of the next month (February) the max value of the CountLog was 10, the diff is 10 - 7 equal to 3 and this way.
[URL]
View 16 Replies
View Related
Sep 19, 2015
Select DATEPART(year, OrderDate) As Years,SO.TotalRevenue
From Sales.Orders S
Cross Apply (Select Sum(SD.Qty*SD.unitprice-SD.discount) As TotalRevenue From Sales.OrderDetails SD where S.orderid = SD.orderid
) SO
Group by DATEPART(year, OrderDate),SO.TotalRevenue
View 7 Replies
View Related
Oct 9, 2015
I have a work database where I implemented a table-valued function. One colleague of mine reported to me that this function gave a Divide by Zero error when executed with some specific values given to its arguments (there are a 15 arguments). Then I started debugging, and I introduced some exit points to the function before its end in order to detect the point where the error appeared, since I don't have access to the database server and I cannot use the debugging tools from remote, due to the network configuration of my office. I can only do attempts on the code to try to find a solution.
Since I didn't manage to get rid of this error, I decided to make a silly and desperate attempt: I put a RETURN statement immediately after the BEGIN of the function body, with the idea that the function should not raie any error if it exit immediately after its beginning, despite the fact that this results in an empty table in return.
The result of my attempt is that the Divide by Zero error is still THERE (!), even if my function looks like
ALTER FUNCTION [dbo][<myFuncName>](...parameters...) RETURNS TABLE (...table definition...) AS BEGIN
RETURN
END
GO
How I can check it.
View 5 Replies
View Related
Dec 5, 2015
How can i subtract two columns:
I have table:
ID COL 1 COL 2
-------------------------
1 200.00 70.00
2 200.00 30.00
3 200.00 90.00
4 200.00 110.00Col1 - COL2
But to continue for each row and value is reduced by the previously value.
My output should be like as:
ID COL 1 COL 2 [COL3 AS RESULT]
-------------------------
1 200.00 70.00 130
2 200.00 30.00 100
3 200.00 90.00 10
4 200.00 110.00 -100
View 3 Replies
View Related
Sep 14, 2015
I used the MERGE function for the first time. Now I have to create a pipe-delimited delta file for a 3rd party client of any deltas that may exist in our database.
What is the best way to do this? I have OUTPUT to a result set of the deltas...but I have to send over the entire table to the 3rd party via a pipe-delimited file.
View 5 Replies
View Related
Aug 7, 2015
Well adding it to a group by or function skews the result set. How to write this query so it displays as I need it to? This is what I have thus far, and it works as it should UNTIL I add in the line of
cast(cte.[C] As float)/cast(sum(cte.[C]) over() as float)*100 As [Rate1],
Presents the error of:
Msg 8120, Level 16, State 1, Line 35
Column 'cte.[C]' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
This is my full on query -- with 3 CTE's involved to get me the actual result set I am after.
;with cte as
(
select
[state],
case when exists (select 1 from table2 R where R.centername = d.centername) then 1 else 0 end as [L],
case when exists (select 1 from table3 C where C.centername = d.centername) then 1 else 0 end as [C]
FROM maintable d
),
[Code] .....
View 4 Replies
View Related
Nov 3, 2015
I have a function which accepts table parmeter. i have created a view and i need to use this function.
How can i do it. how can i pass dim table into the @table variable
select * from dim cross apply fnc_user(@table variable)
View 4 Replies
View Related