Transact-SQL IsXML Function (wish)

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


ADVERTISEMENT

A Transact SQL Function -urgent! -

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

Transact SQL :: Right Function With Delimiter

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

Transact SQL - Does It Have The Equivalent Of FINDONEOF Function?

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

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 View Related

Trying To Call The Function A Web Service From Transact-SQL

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

Diffrence Between Metadata Function And Transact-SQL

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

Transact SQL :: Summing With A Function In Grouping

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

Transact SQL :: Top Percent In A Window Function OVER

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

Transact SQL :: Using Aggregate Function With Subquery?

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

Transact SQL :: How To Use Divide Function In Query

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

Transact SQL :: Passing Parameters Through SP To A Function

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

Transact SQL :: Modify URL With Replace Function

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

Transact SQL :: Simple Count Function

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

Is It Possible To Extend SQL-TRANSACT With User-defined Function

Jun 20, 2000

View 3 Replies View Related

Transact SQL :: Storing Parameter Value Used By Scalar Function

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

Transact SQL :: Duplicate PIVOT Function In 2000

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

Transact SQL :: Advanced Query With Windows Function?

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

Transact SQL :: Convert Sub-query Into Scaler Function?

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

Transact SQL :: Divide By Zero Error In Empty Function

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

Transact SQL :: Subtract Two Columns With Windows Function

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

Transact SQL :: MERGE Function And OUTPUT To A File

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

Transact SQL :: Invalid Due To Not Being In Group By Or Aggregate Function

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

Transact SQL :: Passing Table Parameter To A Function

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

Transact SQL :: GetDate Function Not Returning Any Results?

May 27, 2015

I am having a problem with the GETDATE().

WHERE TableName.ColumnNamne = Getdate()

The above SQL function does not return any results whereas the below SQL code returns results. Am I doing anything wrong?

WHERE SalesOrder.New_ActualShipmentDate >= GETDATE()

View 35 Replies View Related

Transact SQL :: Get 2 Different Result Sets With GetDate Function

Aug 4, 2015

Periodically throughout the day a report is manually pulled from a SQL Server database.  Is their a way w/o me adding a field to the database to have the result set return the "new" results?  For example, lets say this is our DDL

Create Table OneTwoThree
(
id int
,date11 datetime
,firefly varchar(10)
)

Insert Into OneTwoThree Values (1, '08/03/2015 18:43:32.012', 'Hi'), (2, '08/03/2015 18:44:11.011', 'No'),
(3, '08/03/2015 19:36:33.011', 'Second'), (4, '08/03/2015 19:37:33.011', 'Alpha')

Prior I could use this syntax, but that was only with needing to generate 1 result set.  

Select id, convert(varchar(10), date11, 101) As [Date], firefly from onetwothree
where CONVERT(varchar(10), date11, 101) < CONVERT(varchar(10), GetDate(), 101)

Looking at my datetime values, let's say the 1st was generated at 18:45, obviously the 1st two records in the table would be returned. And let's say a 2nd time I need to generate I want to exclude the 1st two entries as they have already been verified. How can I do such w/o adding a field to the table?

View 11 Replies View Related

Why These Two SQL Statement Return Differently? Using ROUND() Function In Transact-SQL

Sep 19, 2007

Hello, DECLARE @x DECIMAL
SET @x = 65.554
SELECT ROUND(@x, 1)--this returns 66

SELECT ROUND(65.554, 1)--this returns 65.600 can someone explain to me why is like that?
 Thank you
 

View 3 Replies View Related

Transact SQL :: String Function To Extract Matching Rows

Oct 6, 2015

Consider the following: I have a table, say ORDERS, with these entries -

CustID
ProductID
1       CAN
2       2
3       1,2
4       4
5       1,2,3,4,5,CAN
6       10
7       CAN
8       1,CAN

I'd like to write a script to return only those rows WHERE ProductID = CAN along with other values in the same column. In this example, I'd like to return rows 5 & 8. How can I write this in T-SQL? So, say, check if ProductID has a comma ',' value plus the 'CAN' string. If yes, then return that row. If I use the LIKE operator, it'll return rows 1,5,7, and 8.

View 12 Replies View Related

Transact SQL :: Not Allowed To Write Delete Statements In A Function?

Jun 25, 2015

We are not allowed to write delete statement in a function. It will give the below error.

"Invalid use of a side-effecting operator 'DELETE' within a function."

We will get the same error for truncate/drop statements.

What is the reason behind this error?

View 8 Replies View Related

Transact SQL :: Create A Function To Define Query-filter

Jul 6, 2015

Is there a way to define a query-filter (Example: WHERE column1 > 5 AND column2 = 'value') in a function?

So I can create a query like this:

SELECT *
  FROM Table
  WHERE MyFunction()

I know it's a bit of a strange question, but I'm writing a dynamic software that will have the ability to run Stored Procedures on any database to create some data-checks. Through parametrisation, a user can define for a specific Stored Procedure that some results are no longer necessary in the result-set.

Example:
ID - Name - State
1 - Jozef De Veuster - Mad
2 - Piet Husentruut - Not Happy
3 - Jeroen Meus - Angry

Is the result of a Stored Procedure "Show_me_unhappy_persons". But we already know that Jozef De Veuster is ALWAYS Mad, so a user can say: Exclude ID = 1, so it won't appear anymore in the result.

I want to handle this by doing:

SELECT *
FROM PeopleStates
WHERE --Some stuff--
AND CheckUserExclusions(SomeID)
And CheckUserExclusions will translate to "NOT (ID = 1)"

View 14 Replies View Related

Transact SQL :: Extracting From 3 Related Tables And Including MAX Function

Oct 5, 2015

I have these 3 tables in a database for printed chamber music works:

Table INSTRUMENTS: List of musical instruments
    Column ID          -- int, primary key
    Column sInstrument -- string

Table PTRS_INSTRUMENTATION: 
    Column ID          -- int, primary key
    Column lInstrument -- int, points to a row in table INSTRUMENTS via ID
    Column lMainItem   -- int, points to a row in table MAINITEMS via ID
    Column lInstrSeqNum -- int, sequential number of like instruments within one Main Item
    
Table MAINITEMS: List of chamber music works
    Column ID          -- int, primary key
    Column sItem       -- string
    
Each chamber music work (Main Item) requires an ensemble of musicians playing several instruments. Some of them may be the same, such as 2 violins. A classical quartet, for instance, consist of 2 violins, 1 viola and 1 cello. I am concerned here only with one of the instruments (although it may occur several times).

I want to extract a list of Main Items where the instrument is given (e.g., 'violin'),

And the maximum of PTRS_INSTRUMENTATION.lInstrSeqNum is a given number (e.g., 2).

View 7 Replies View Related

Transact SQL :: Return A Query Based On Dateadd Function

Aug 3, 2015

I'm trying to return a query based on the dateadd function.  I have a column in the database called date_added which is am successfully using the the DATEADD function above as date1.  The Var1 variable I need to populate from the database too from a column called life_span which is an int data type.  The error I get is An expression of non-boolean type specified in context where a condition is expected near select

My query is as follows: select guid, dateadd(day,life_span,date_added) as datepayday. From User_table

View 5 Replies View Related

Transact SQL :: How To Execute Insert Statement With A Function Call

May 20, 2015

I have a function like below

CREATE FUNCTION [dbo].[UDF_GetCode] 
(
@TableName NVARCHAR(50)
)
RETURNS NVARCHAR(50)

[code]...

This function is called in insert statement like below. exec sp_executesql N'INSERT INTO Table ([Code], [Name]) VALUES (dbo.UDF_ GetGlobal ConfigCode (''TableName''), @Name)'I am getting following error.Only functions and some extended stored procedures can be executed from within a function.

View 3 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved