Query Question - Check Before Insert

Dec 1, 2003

I have a table, emailaddresses with an emailaddress field.





before i do an insert from a stored proc, i want to check if the emailaddress is already in the database.





pseudo-code:





if emailaddresssparameter is IN emailaddress then


do not insert


else


insert into table


end





i've got the insert statement and the stored proc, but how do i write the check to see if it's already there? I mean i could do a select * from emailaddress wehre emailaddress=emailaddressparam





but how to i test it? if the count=1 then skip?





here's my proc now:





ALTER PROCEDURE dbo.AddOneEmailAddress





(


@emailAddress varchar(255),


@emailID int=0 OUTPUT


)





AS


/* SET NOCOUNT ON */


insert into EmailAddresses


(email_address)


values


(@emailAddress)


set @emailID=@@identity





RETURN @@identity

View 2 Replies


ADVERTISEMENT

Performing Insert Query With Check

Feb 29, 2008

hii,,i am using asp.net 2005 and sql server 2005.i have a web page in which i can enter details and it gets stored in a table in a database..in the table thrs a column called as sme_id,,what i want is when one inserts a new sme_id from the page,,it should check in the table so tht no duplicate sme_id wil b generated..,,this code is workin fine,,i just want to implement the above condition...here is the insert code which i have used along with sql datasource:::__________________________
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConflictDetection="CompareAllValues"
ConnectionString="<%$ ConnectionStrings:sme_trackerConnectionString %>"
InsertCommand="INSERT INTO SME_Master(SME_Id, FirstName, LastName, Type_of_SME, Agency_id, Agency_Name, Email, Address, Phone, Mobile, Fax, TimeZone_Id, Experience, City, State, Status, Level_Of_Exam, Other_Comments, Certificate, Expertise)
 VALUES (@SME_Id, @FirstName, @LastName, @Type_of_SME, @Agency_id, @Agency_Name, @Email, @Address, @Phone, @Mobile, @Fax, @TimeZone_Id, @Experience, @City, @State, @Status, @Level_Of_Exam, @Other_Comments, @Certificate, @Expertise)"
OldValuesParameterFormatString="original_{0}" SelectCommand="SELECT * FROM [SME_Master]">
_______hope u got my problem,,,,,reply asap....thnks in advance

View 11 Replies View Related

Check Before INSERT

Aug 6, 2007

I have a pretty standard form that inserts users name, office, and team. It generates a random 10 digit ID for them. How would i got about checking the table to make sure that ID doesn't exist?
Here's my insert code.
        string strConnection = ConfigurationManager.ConnectionStrings["TimeAccountingConnectionString"].ConnectionString;        SqlConnection myConnection = new SqlConnection(strConnection);
        string usercode = GenPassWithCap(9);
        String insertCmd = "INSERT into users (ID, firstname, lastname, office, team) values (@id, @firstname, @lastname, @office, @team)";        SqlCommand myCommand = new SqlCommand(insertCmd, myConnection);
        myCommand.Parameters.Add(new SqlParameter("@id", SqlDbType.VarChar, 10));        myCommand.Parameters["@id"].Value = usercode;
        myCommand.Parameters.Add(new SqlParameter("@firstname", SqlDbType.VarChar, 50));        myCommand.Parameters["@firstname"].Value = txtFirstName.Text;
        myCommand.Parameters.Add(new SqlParameter("@lastname", SqlDbType.VarChar, 50));        myCommand.Parameters["@lastname"].Value = txtLastName.Text;
        myCommand.Parameters.Add(new SqlParameter("@office", SqlDbType.VarChar, 75));        myCommand.Parameters["@office"].Value = dwnOffice.SelectedValue;
        myCommand.Parameters.Add(new SqlParameter("@team", SqlDbType.VarChar, 20));        myCommand.Parameters["@team"].Value = dwnTeam.SelectedValue;
        myCommand.Connection.Open();
            myCommand.ExecuteNonQuery();
 Do I run a completey different select command before hand and try to match that field?

View 1 Replies View Related

Check Box Insert Question

Dec 10, 2003

I have 3 tables - Data, Facility and FacilityKey

The FacilityKey table will hold the Data ID and Facility ID based on a series of check boxes on a form.

My question is what is the best way to do the insert into the FacilityKey table from the form? If 5 facilities are checked I don't want to do 5 separate calls to the database for inserts, but I'm a bit confused on what the best method would be.

Thank you!

View 1 Replies View Related

Check Data Before Insert

Aug 15, 2007

I need help thinking about this problem :-)

I have an SSIS pkg that automatically downloads financial extracts from an ftp site. Once the files are downloaded, I load the extract to a table. The table is first deleted before the insert, so that each time the table has "fresh" data (whatever was in the extract for that day).

Once the extract data is in the table, I load the data into yet another table that combines data from many tables. Simple enough.

Problem is, sometimes when I download the extract, it hasn't been updated yet, so I'm downloading an OLD extract. This old data then gets loaded into the first table. That's ok, because it doesn't really hurt anything. I can always delete the table and reload it if necessary.

The problem occurs when the old data goes from this table into the OTHER table. We don't want old data in this other table!

I need a way to check that I'm not loading the same data 2 days in a row into the OTHER table.

I realize that I might be able to solve this problem without using SSIS, but the solutions I've come up with so far aren't 100% satisfactory. I can use a query to check dates and that sort of thing, but it isn't foolproof, and would create problems if I need to manually force the process though, that is, if I need to override the date logic.

Anyways, I'm wondering if there's an SSIS approach to this problem... I can't rely on timestamps on the data files either. They're not accurate.

This is has been very perplexing to me.

Thanks

View 8 Replies View Related

Check For Column &&amp; Insert

Jan 7, 2007

Can you tell me if this is possible? (and how to do it!!)

The application is VS2005, with sql database.

I want to check if a specific column exists in a specific table in the database and if not then add it, all via my application.

I'm happy knowing how to connect to the database & pass sql commands (as I'm doing that anyway to set off backups), but not the actual queries I'd need.

View 3 Replies View Related

Help...pls Check What's Wrong....not Able To Do Insert With Sqldatasource

May 9, 2007

Hi frdz,         I m the new user of ASP.NET WEB APPLICATIONS WITH C# LANGUAGE.         I m using SQL SERVER 2005 and SQLDATASOURCE to get or retrieve the data from the database.         I have created the stored procedure for insert and update.         The stored procedure is executing fine when i m running it from sqlserver2005.         My problem is with the web-application page.         I m not able to insert or update data thru that...         Pls check the code and tell me what's missing out ..........SQLDATASOURCE<asp:SqlDataSource ID="srcemp" runat="server" ConnectionString="<%$ ConnectionStrings:empmaster  %>"     InsertCommand="empStoredProcedure" InsertCommandType="StoredProcedure"     UpdateCommand="empStoredProcedure" UpdateCommandType="StoredProcedure"      DeleteCommand="DELETE FROM empmaster          WHERE empid = @empid" DeleteCommandType="Text"     SelectCommand="select * from empmaster " SelectCommandType="Text">     <InsertParameters><asp:Parameter Name="empname" Type="String" /><asp:Parameter Name="address" Type="String" /><asp:Parameter Name="city"  /><asp:Parameter Name="pincode" /><asp:Parameter Name="state" /></InsertParameters> <UpdateParameters><asp:Parameter Name="empname" Type="String" /><asp:Parameter Name="address" Type="String" /><asp:Parameter Name="city"  /><asp:Parameter Name="pincode" /><asp:Parameter Name="state" /></UpdateParameters>     </asp:SqlDataSource>GRIDVIEW  <asp:GridView ID="empGridView" runat="server" AutoGenerateColumns="False"         DataKeyNames="empid" DataSourceID="srcemp"         Width="56px" >             <Columns>    <asp:TemplateField>    <ItemTemplate>    <asp:LinkButton ID="btnDelete" runat="server" CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete this row ?');">Delete</asp:LinkButton>    </ItemTemplate>    </asp:TemplateField>                                                  <asp:boundfield datafield="empname"            headertext="emp Name"/>           <asp:boundfield datafield="address"            headertext="Address"/>          <asp:boundfield datafield="city"            headertext="City"/>         <asp:boundfield datafield="state"            headertext="State"/>                                     <asp:CheckBoxField            DataField="deleted"            HeaderText="In Existance" />            </Columns>          </asp:GridView>C# code protected void cmdsubmit_Click(object sender, EventArgs e)    {        srcemp.InsertParameters["empname"].DefaultValue = tbcompanyname.Text;        srcemp.InsertParameters["address"].DefaultValue = tbaddress.Text;         srcemp.InsertParameters["city"].DefaultValue = tbcity.Text;        srcemp.InsertParameters["pincode"].DefaultValue = tbpincode.Text;        srcemp.InsertParameters["state"].DefaultValue = cmbstate.SelectedItem.ToString();         srcemp.Insert();}Note :I m not getting a single error msg for the above code in web-page or stored procedure but it does not insert,update or delete the record from the database....Thanxs in adv...pls reply at earliest if possible...What's missing ??can anyone check out..what's wrong ??

View 1 Replies View Related

How To Check If Sql Insert Command Was Successful

Jan 14, 2008

I'm running a pretty standard insert command on a button (myCommand.ExecuteNonQuery();)
 I have a few other methods that run, but I only want them to proceed if the above was inserted successfully, how would i check that?

View 8 Replies View Related

SSIS: Check -&&>Update -&&>Insert

Sep 7, 2007

I have two tables from two different Databases

DB1.dbo.Table1 and DB2.dbo.Table2

eX:

Table 1
KEY LName FName Updated
1 GYM ABC Y
1 TIM ABC N
1 PIN ABC N
2 QWE SAD Y
......
....


Table 2
KEY LName FName Updated
1 JIM ABC Y
2 QWE SAM Y

....
....


1) Table 1 and Table 2 are of same structure.
2) In table2, as in above example, few changes have beeen done for KEY1 AND Update =Y, Similarly KEY= 2 AND UPDATED=Y, like for KEY= 1 LName was changed to JIM instead of GYM and for KEY= 2 FName has been changed to SAM instead of SAD.

3) Now I want to do this in SSIS where
a) Its going to process rows of Table2 and check in table1 according to KEY and UPDATE=Y and update the Table1 with Updated = N and Insert that particulra process row of Table2 into Table1

and hence Resultant of Table1 must be like this

Table 1
KEY LName FName Updated
1 GYM ABC N
1 TIM ABC N
1 PIN ABC N
1 JIM ABC Y

2 QWE SAD N
2 QWE SAM Y
......
....

Can somebody help me how to do this in SSIS. Thnaks a lot in advance

View 1 Replies View Related

How To Check If An Insert Stored Proc Succeeded

Mar 5, 2007

Hi,
How would I check if an insert via stored proc succeeded? Here's the proc I'm using:set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:<Author,,Name>
-- Create date: <Create Date,,>
-- Description:<Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[showtube_addNewSUser]
-- Add the parameters for the stored procedure here
@UserId uniqueidentifier,
@FirstName nvarchar(32),
@LastName nvarchar(32),
@DescShort nvarchar(256),
@DescLong ntext,
@ClanID uniqueidentifier
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here
Insert into dbo.Users (UserId, FirstName, LastName, DescShort, DescLong, ClanID)
values (@UserId, @FirstName, @LastName, @DescShort, @DescLong, @ClanID);
END


 
 
I tried adding a Return @@RowCount before the END statement, but it always seems to return -1. Could someone tell me what I'm doing wrong? Thanks.

View 3 Replies View Related

Package For Update/insert And Check For New Record

Apr 21, 2008

hi,

i'm total newbee on SSIS packages and therefore need guidance.

I want to make a ssis package that (in order):

- check in table (tbl_orders) if there is any new order made
- if new order is made, update column (time_last_change)
- if this order has geography ID (ID_geography) inserted, insert name of geography.

Thank you in advance,

View 2 Replies View Related

The INSERT Statement Conflicted With The CHECK Constraint

Jan 8, 2008

Hi, I am new to MS SQL Server; as I know Access, MYSQL. I made a form though which I want to insert data to SQL SERVER 2005 Database but i during submission I get the below problem, can any one help.


Microsoft OLE DB Provider for ODBC Drivers error '80040e14'

[Microsoft][ODBC SQL Server Driver][SQL Server]The INSERT statement conflicted with the CHECK constraint "SSMA_CC$Bcast$msgHTML$disallow_zero_length". The conflict occurred in database "x485i", table "dbo.Bcast", column 'msgHTML'.

/html/n_.asp, line 193

Best Regards,
Imran

View 3 Replies View Related

Create Trigger To Check Values At Insert/update

Feb 10, 2004

I have never used triggers before and I have tried to solve one problem. If I have the column "currency" in a table and want to make sure that the entered value i valid in relation to another table that contains valid currency formats, I did it like this:

---------------------------------
CREATE TRIGGER [trigger_checkCurrency] ON [dbo].[Client]
FOR INSERT, UPDATE
AS
declare @currency as char(50)
declare @country as char(50)

declare cur cursor for SELECT currency, country
FROMinserted

OPEN cur
fetch cur into @currency, @country
WHILE @@FETCH_STATUS = 0
BEGIN
if not exists(select * from listinfoid where listname = 'currency' and listid = @currency)
begin
set @currency = (cast(@currency as varchar (3)) + ' is not a valid currency')
CLOSE cur
DEALLOCATE cur
RAISERROR (@currency,16,-1) with log
return
end
if not exists(select * from listinfoid where listname = 'country' and listid = @country)
begin
set @country = (cast(@country as varchar (3)) + ' is not a valid contry')
CLOSE cur
DEALLOCATE cur
RAISERROR (@country,16,-1) with log
return
end
else
fetch cur into @currency, @country

END
CLOSE cur
DEALLOCATE cur
update Client set currency = UPPER(currency), country = UPPER(country)
---------------------------------



I use a cursor to handle multiple rows in an update query.
(SQL2000-server)

Is there an easier och better way to do this?
I´m a bit unsure of this code.

Thanx!

/Erik

View 2 Replies View Related

Insert Stored Procedure With Error Check And Transaction Function

Jul 21, 2004

Hi, guys
I try to add some error check and transaction and rollback function on my insert stored procedure but I have an error "Error converting data type varchar to smalldatatime" if i don't use /*error check*/ code, everything went well and insert a row into contract table.
could you correct my code, if you know what is the problem?

thanks

My contract table DDL:
************************************************** ***

create table contract(
contractNum int identity(1,1) primary key,
contractDate smalldatetime not null,
tuition money not null,
studentId char(4) not null foreign key references student (studentId),
contactId int not null foreign key references contact (contactId)
);


My insert stored procedure is:
************************************************** *****

create proc sp_insert_new_contract
( @contractDate[smalldatetime],
@tuition [money],
@studentId[char](4),
@contactId[int])
as

if not exists (select studentid
from student
where studentid = @studentId)
begin
print 'studentid is not a valid id'
return -1
end

if not exists (select contactId
from contact
where contactId = @contactId)
begin
print 'contactid is not a valid id'
return -1
end
begin transaction

insert into contract
([contractDate],
[tuition],
[studentId],
[contactId])
values
(@contractDate,
@tuition,
@studentId,
@contactId)

/*Error Check */
if @@error !=0 or @@rowcount !=1
begin
rollback transaction
print ‘Insert is failed’
return -1
end
print ’New contract has been added’

commit transaction
return 0
go

View 1 Replies View Related

Can You Please Check Out My Sql Query And Tell Me What's Wrong With It? Thank You

Jul 20, 2007

the error message shows it's now allow " =�!=�<�<=�>�>=" after sub query..
 
Select * From ZT_MediaImportLog Where isNumeric(ImportFileTime) = 1 And ImportFileTime < Convert(varchar(10),DateAdd(Month,-CAST                              (( select keepmonth from ZT_MediaImportLog, ZT_BillerChain a,ZT_BillerInfo b,ZT_Biller c,ZT_databackup d where a.BillerInfoCode = b.BillerInfoCode AND c.CompanyCode = d.Companycode AND ZT_MediaImportLog.Importsource = a.ChainCode ) AS int),GetDate()),112)

View 6 Replies View Related

SQL Query To Check Against A List

Jul 23, 2005

SQL gurus...I have one table of items that is the master file. We will call this Table A.I have another table that contains few, some or all items from Table A. Wewill call this Table B.I want to run a query that compares the list of items on Table B against themaster list on Table A.If the item is not present on Table B, show it in the SQL results.Best way to achieve this? I am looping and doubling results in my sql tries.Jeff--Message posted via http://www.sqlmonster.com

View 1 Replies View Related

Check Query Status

Sep 26, 2007

Is it possible to create an SSIS package that checks for a running Query on my SQL db?
I need to some how check my SQL server and see if there is a query running, if its running I need to set an indicator in my table for my app. This job needs to be scheduled and run nightly (which I can do). But how can I query SQL and see if the query is still running?


View 4 Replies View Related

Query With Multiple ID To Check And Response...

Jan 27, 2007

Hi there, I tried to make it different as usual but i´m stacked into this problem:Supose TABLE DetailsID_DET    ID_CAR    DETAILS1              3             1,2,3,4,5,62              4             2,43              5             5,6,7,8andTABLE  Details_ItemsID_DI       DETAIL_NAME1             Stereo HiFi CD2             Alarm3             AirConditioning4             LeatherSeats5             Pro Wires6             Aluminium WheelsThe problem appears when i need to bring CAR DETAILS (NAME) from TABLE DETAIL_ITEMS.Mi guess i that I should make something like:SELECT * FROM DETAILS_NAME WHERE id_di = ((  Array(i) FROM  Details  )) one by one...I really dont know how to face it.First I thought in bringing ALL details_Items (datafieldtext = id_di and datavaluetext=Details_names) into a dataview.And then "somohow?" filter this dataview according with the Array previuosly splited by me with a For each function.Then I thought "Perhaps" there is a simpliest way to do that using SQL views, o advanced SQL QUERYS.and Finally I thought that creating a VIEW in for both TABLES would be great.The point is that, neither 1,2,3 options, honestly , I dont know how to face them.Thanks in advance, apologise my "rude" English grammar.LUCAS ( From Argentina )
 
 
 

View 2 Replies View Related

SQL Query Check And Validate (Urgent)

Jan 9, 2007

Hello All,

It seems the following queries are causing my DB connections to time out, but I cant seem to figure out why.

These queries reside within my xml.config file.

The connection to the DB is fine and live. I get timeout errors every few hours or so.

Can anyone take a look at the queries which I pasted below and tell me why I keep getting timeout errors? PLEASE, I need all the help I can get.

<query name="Products" rowElementName="Product">
<sql>
<![CDATA[
SELECT p.*,
pv.VariantID, pv.name VariantName, pv.Price, pv.Description VariantDescription, isnull(pv.SalePrice, 0) SalePrice, isnull(SkuSuffix, '') SkuSuffix, pv.Dimensions, pv.Weight, isnull(pv.Points, 0) Points,
sp.name SalesPromptName,
isnull(e.Price, 0) ExtendedPrice
FROM Product p
join productvariant pv on p.ProductID = pv.ProductID
join SalesPrompt sp on p.SalesPromptID = sp.SalesPromptID
left join ExtendedPrice e on pv.VariantID=e.VariantID and e.CustomerLevelID=@CustomerLevelID
WHERE p.ProductID = @ProductID
and p.Deleted = 0
and pv.Deleted = 0
and p.Published = 1
and pv.Published = 1
ORDER BY p.ProductID, pv.DisplayOrder, pv.Name
]]>
</sql>
<queryparam paramname="@CustomerLevelID" paramtype="runtime" requestparamname="CustomerLevelID" sqlDataType="int" defvalue="0" validationpattern="" />
<queryparam paramname="@ProductID" paramtype="request" requestparamname="ProductID" sqlDataType="int" defvalue="0" validationpattern="^d{1,10}$" />
</query>

<query name="Ratings" rowElementName="Rating">
<sql>
<![CDATA[
SELECT ProductID, CAST ( AVG(CAST(Rating AS decimal)) as decimal (10,2)) as Rating
FROM Rating
WHERE ProductID = @ProductID
Group By ProductID
ORDER BY ProductID
]]>
</sql>
<queryparam paramname="@ProductID" paramtype="request" requestparamname="ProductID" sqlDataType="int" defvalue="0" validationpattern="^d{1,10}$" />
</query>

<query name="TotalRatings" rowElementName="TotalRating">
<sql>
<![CDATA[
SELECT ProductID, Count(Rating) as TotalRating
FROM Rating
WHERE ProductID = @ProductID
Group By ProductID
ORDER BY ProductID
]]>
</sql>
<queryparam paramname="@ProductID" paramtype="request" requestparamname="ProductID" sqlDataType="int" defvalue="0" validationpattern="^d{1,10}$" />
</query>

<query name="popup" rowElementName="popit">
<sql>
<![CDATA[
SELECT ProductID as rateID
FROM Product
WHERE ProductID = @ProductID
Group By ProductID
]]>
</sql>
<queryparam paramname="@ProductID" paramtype="request" requestparamname="ProductID" sqlDataType="int" defvalue="0" validationpattern="^d{1,10}$" />
</query>

View 9 Replies View Related

Query Response Time Check

Sep 28, 2006

Is there a global variable or something of the sort that would tell me how long it took to execute a query??

I need to monitor my DB response times and we have a query that runs in under 2 seconds. So we want to run this query every couple of minutes and if it takes more than 12 sec to run, we want to send an email to our DB staff...

I know that I could take a time stamp before and after then subtract but I wanted to know if there was an easier way to do it..

Thanks.

View 3 Replies View Related

How To Check Multiple Records With One Query

Sep 3, 2007

i have a table which is having size and pieces information and say it is having following 4 records.



Size, pieces, sizeID, sizecombID (SizeCombination Id)

S, 1, 1, 1

M, 3, 2, 1

L, 3, 3, 1

XL, 1, 4, 1



Now suppose user enters all these 4 records which i will pass as xml string to my stored procedure.

Is there any way to check existense of all these 4 records in this table from the xml data which i pass by using one SQL statement ? Or what is the right way of checking it, Is it through using cursor ??

Finally after checking it should retrun SizeCombID for a existing record, and if record is not existent then it should add these 4 records in table and return the new SizeCombID.

Can somebody pls help on this..

View 7 Replies View Related

Wants To Insert Into Multiple Table By A Single Insert Query

Apr 11, 2008

Hi,ALL
I wants to insert data into multiple table within a single insert query
Thanks

View 3 Replies View Related

Can You Check My Select Max Query ? The Result Not Corret...

Aug 1, 2007

in table Databackup
company       keepmonth
-----------------  -------------------
001                 12002                 12003                  6005                  607917              609747              6
 
I run this query
select Max(keepmonth) as keep from Databackup
why the result is 6 not 12? I think the max value should 12 , have no idea why it return 6
does my query error?
thank you

View 1 Replies View Related

How To Check If Results Of Dynamic Query Exist

Dec 27, 2001

Hello,

I have a dynamic query in the stored procedure, and the code looks something like this:

SET @section_test = 'SELECT sectioncode FROM ' + @tablename + ' WHERE sectioncode = "' + @condition + '"'
EXEC (@section_test)

What I need to do is try to check if the query returns any values using EXISTS (possibly), but at the same time I don't want to return the results of that dynamic query's select statement in my stored procedure. Is it possible?

Thanks.

Regards,
Katya

View 1 Replies View Related

Query Analyser Does Not Check For Object Existence

Nov 27, 2000

we tried out the following code in query analyser -

create procedure TrialProc

as

select * from sakjdhf


when we executed this piece of TSQL in query analyser, we expected it to give an error or warning that no object by the name of sakjdhf exists ( as actually there is no such table or view in the database ). however to our surprise we got "command completed successfully " !!

does this mean the SQL server does not check for necessary objects when creating a stored procedure ? or is there some setting that we missed out whihch is causing SQL server to overlook the error in the code ?

View 3 Replies View Related

Check Multiple Parameter Instead Of Dynamic Query?

Oct 20, 2014

how to check multiple parameter instead of dynamic query.

View 1 Replies View Related

Query Or Script To Check Link Table

Mar 23, 2008

i'm pretty familiar w/ mysql, but relatively new to ms sql. Since i can do a lot more w/ ms sql, I have been trying to do all tasks in sql queries or scripts, but i'm stumped on this one. I have a table that links two things together. t1 has rows id1 and id2. When a row has these two id's, there is a "link" between them. I'm trying to make a command or script that will see if there is only 2 links for any given id.

for example, it would loop through each row, and run this command:

SELECT COUNT(*) AS Expr1
FROM links
WHERE (Id1 = this_rows_id1) OR (Id2 = this_rows_id1)

and again w/ id2

and then i would be interested in any row that only had a count of 2. is this possible?

View 2 Replies View Related

Query - Check For A String In Stored Procedure

Jul 23, 2005

Hi,I would like to check if a string value exist in a string in sqlserver stored procedure, e.g.set @testString = 'this is my test document.'if (@testString contains 'test')begin.....endHow do I do this in sql server stored procedure?Thanks,June...

View 1 Replies View Related

How To Check If A Table Is Empty Using Query Code

Aug 9, 2013

I want to check if a table is empty using query code?

How to do this?

View 4 Replies View Related

Transact SQL :: Query - How To Check For Special Characters

Aug 21, 2015

query that checks to see if a variable contains special characters; except for hyphens, periods, and accents?

View 3 Replies View Related

Query Performance On Paritioned Views With Check Constraints

Mar 21, 2007

Hi,

I have come across this problem with SQL server both on 2000 and 2005. I am stating an example here.

I have two partitioned tables and a view on top of both tables as below:
create table [dbo].[Table_1]
(
[TableID] INTEGER PRIMARY KEY NONCLUSTERED
CHECK NOT FOR REPLICATION ([TableID] BETWEEN 1 AND 999),
[AnyOtherColumn] int NOT NULL ,
) ON [Primary]
GO

create table [dbo].[Table_2]
(
[TableID] INTEGER PRIMARY KEY NONCLUSTERED
CHECK NOT FOR REPLICATION ([TableID] BETWEEN 1000 AND 1999),
[AnyOtherColumn] int NOT NULL ,
) ON [Primary]
GO
create view TableView
as
select * from Table_1
union all
select * from Table_2
GO

Note the NOT FOR REPLICATION clause on the check constraint on the TableID column.

I then ran the query execution plan for the following query on both SQL server 2000 and 2005.
select * from TableView where TableID = 10

On both the versions the execution plan shows and Index seek on both the tables in the view. This means that my partitioning is not working. If I remove the primary key constraint from the TableID column, the same query on the view shows a table scan on all the underlying tables. This is even worse.

Next, create the same tables and views again, now without the NOT FOR REPLICATION clause on the check constraint as show below:
create table [dbo].[Table_1]
(
[TableID] INTEGER PRIMARY KEY NONCLUSTERED
CHECK ([TableID] BETWEEN 1 AND 999),
[AnyOtherColumn] int NOT NULL ,
) ON [Primary]
GO

create table [dbo].[Table_2]
(
[TableID] INTEGER PRIMARY KEY NONCLUSTERED
CHECK ([TableID] BETWEEN 1000 AND 1999),
[AnyOtherColumn] int NOT NULL ,
) ON [Primary]
GO

create view TableView
as
select * from Table_1
union all
select * from Table_2
GO



Now run the query execution plan for the same query again.




select * from TableView where TableID = 10

This time you would see that it does an index scan only on the first parititon table. This time it proves that the partitioning works.

I would like to know why does the NOT FOR REPLICATION clause in the check constraint make such a huge difference?

Is it a bug in SQL server?

Or am I missing any thing?

Any help appreciated.

Thanks

View 2 Replies View Related

Analysis :: Check To See If A Measure Is Of Certain Data Type In MDX Query

May 8, 2015

I am using the following approach to enable dynamic date calculations: [URL] ...

However, some measures I work with are percentages (not numeric values) and demand a different formula.

See example snippet bellow (first IIF statement)

/*Calendar*/
[Date Calculation].[Calculation].[Calendar Actual versus PY WK %] =
IIF
(
[measures].Name = "HSP2 %", -- < ThIs is where I am trying to check if the measure is a percetgae type
0, -- < When this is the case then do something different

[Code] ....

I am trying to access the metadata. I am aware of $system.mdschema_measures but I am unable to utulize this for my case.

View 6 Replies View Related

Check System Date Format And Then Change It Thru SQL Query.

Nov 4, 2007



Hi All,

Is it possible to check the local system date format and then change the format to another format using SQL command in VB.

Eg.

-check current system format dd/MM/yyyy
-change current system format to MM/dd/yyyy format

Thanks
Jam.

View 12 Replies View Related







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