Click here to Skip to main content
15,886,799 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Suppose I have four databases in my project and I would like to validate a Mobile number but i want to check that that mobile number is also not present in the remaining three databases.

How to do that ?


What I have tried:

Tried Googline but didnt get much info.
Posted
Updated 30-Nov-18 2:20am
Comments
Sinisa Hajnal 30-Nov-18 2:10am    
Connect to each in turn and check. If you need speed, create fifth "common" database that will sync and index the data you need to check (mobile numbers) and check only that one. More setup initially, but much faster than using four connections.

1 solution

Create a Stored Procedure with 2 parameters (input PhoneNumber, output Exists) that contains a UNION query for all 4 tables. Then in C# you can call that Stored Procedure with those 2 parameters and find out if it exists or not.

SQL Stored Procedure
SQL
CREATE PROCEDURE dbo.usp_PhoneNumberCheck (
	@PhoneNumber	NVARCHAR(100),
	@Exists		BIT	OUTPUT	= 1
) 
AS
BEGIN
	; WITH cte AS (
		SELECT PhoneNumber FROM DatabaseName1.SchemaName.TableName
		UNION
		SELECT PhoneNumber FROM DatabaseName2.SchemaName.TableName
		UNION
		SELECT PhoneNumber FROM DatabaseName3.SchemaName.TableName
		UNION
		SELECT PhoneNumber FROM DatabaseName4.SchemaName.TableName
	)

	IF NOT EXISTS ( SELECT 1 FROM cte WHERE PhoneNumber = @PhoneNumber) BEGIN
		SET @Exists = 0
	END
END
GO


C# method guts
C#
string PhoneNumber = "9115551212"; // placeholder
bool NumberExists = true;

using (SqlConnection conn = new SqlConnection("ConnectionString")) {
	SqlCommand cmd = new SqlCommand("dbo.usp_PhoneNumberCheck", conn);
	cmd.CommandType = CommandType.StoredProcedure;

	SqlParameter outputExists = new SqlParameter("@Exists", SqlDbType.Bit) {Direction = ParameterDirection.Output};

	cmd.Parameters.AddWithValue("@PhoneNumber", PhoneNumber);
	cmd.Parameters.Add(outputExists);

	conn.Open();
	cmd.ExecuteNonQuery();

	NumberExists = outputExists.value;

	conn.Close();
}
 
Share this answer
 
v2
Comments
Dave Kreskowiak 30-Nov-18 8:59am    
It's not 4 different tables the OP is checking. It's four different tables in four different databases.
MadMyche 30-Nov-18 9:51am    
I have updated the solution to reference tables as db.schema.table syntax

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900