QUERY WEB SERVICE FROM SQL SERVER

Database query

WHAT IS A QUERY IN SQL?

A query is a request for data or information from a database table or combination of tables. This data may be generated as results returned by Structured Query Language (SQL) or as pictorials, graphs or complex results, e.g., trend analyses from data-mining tools.

One of several different query languages may be used to perform a range of simple to complex database queries. SQL, the most well-known and widely-used query language, is familiar to most database administrators (DBAs).

For a machine to understand a request for information in the first place, the query must be written according to a code known as query language. For example, if you go to a bank and ask “Can I have an espresso?” the teller might be puzzled.

SQL represents one of the standard languages used for database management purposes, while MySQL, instead, is the software using that specific language. Although SQL is a fairly universal query language, other commonly used ones include DMX, Datalog and AQL.

The query database feature is equal in necessity to data storage capability. Thus, a number of query languages have been developed for different database engines and purposes, but SQL is by far the most ubiquitous and well-known. In fact, rookie database administrators often are surprised when they learn about the existence of other query languages.

Query languages generate different data types according to function. For example, SQL returns data in neat rows and columns and is very similar to Microsoft Excel in appearance.

Other query languages generate data as graphs or other complex data manipulations, e.g., data mining, which is the deep analysis of information that uncovers previously-unknown trends and relationships between distinct or divergent data. For example, a SQL manufacturing company query may reveal that monthly sales peak in June and July, or that female sales representatives continually outperform male counterparts during holiday months.

A database can be queried by less experienced users who are not trained in a specific query language. Using a pre-defined query written in a special query language to make a request isn’t the only way to request information from a database.

WHAT IS SQL SERVER?

Microsoft SQL Server is a relational database management system developed by Microsoft. As a database server, it is a software product with the primary function of storing and retrieving data as requested by other software applications—which may run either on the same computer or on another computer across a network

HOW DOES A QUERY WORK?

How a query works in SQL?

SQL Query mainly works in three phases . 1) Row filtering – Phase 1: Row filtering – phase 1 are done by FROM, WHERE , GROUP BY , HAVING clause. 2) Column filtering: Columns are filtered by SELECT clause. 3) Row filtering – Phase 2: Row filtering – phase 2 are done by DISTINCT , ORDER BY , LIMIT clause.

How does query work in database?

A query works the same way. It gives meaning to the code used in any query language. Be it SQL or anything else, both the user and the database can always exchange information as long as they ‘speak’ the same language. The software, by default, has lists of parameters on their menu

Types of SQL

Here are five types of widely used SQL queries.

  • Data Definition Language (DDL)
  • Data Manipulation Language (DML)
  • Data Control Language(DCL)
  • Transaction Control Language(TCL)
  • Data Query Language (DQL)
Types of SQL

Let see each of them in detail:

What is DDL?

Data Definition Language helps you to define the database structure or schema. Let’s learn about DDL commands with syntax.

Five types of DDL commands in SQL are:

CREATE

CREATE statements is used to define the database structure schema:

Syntax:

CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]); 

For example:

Create database university;
Create table students;
Create view for_students;

DROP

Drops commands remove tables and databases from RDBMS.

Syntax

DROP TABLE ;

For example:

Drop object_type object_name;
Drop database university;
Drop table student;

ALTER

Alters command allows you to alter the structure of the database.

Syntax:

To add a new column in the table

ALTER TABLE table_name ADD column_name COLUMN-definition; 

To modify an existing column in the table:

ALTER TABLE MODIFY(COLUMN DEFINITION....);  

For example:

Alter table guru99 add subject varchar; 

TRUNCATE:

This command used to delete all the rows from the table and free the space containing the table.

Syntax:

TRUNCATE TABLE table_name;  

Example:

TRUNCATE table students;

What is Data Manipulation Language?

Data Manipulation Language (DML) allows you to modify the database instance by inserting, modifying, and deleting its data. It is responsible for performing all types of data modification in a database.

There are three basic constructs which allow database program and user to enter data and information are:

Here are some important DML commands in SQL:

  • INSERT
  • UPDATE
  • DELETE

INSERT:

This is a statement is a SQL query. This command is used to insert data into the row of a table.

Syntax:

INSERT INTO TABLE_NAME  (col1, col2, col3,.... col N)  
VALUES (value1, value2, value3, .... valueN);  
Or 
INSERT INTO TABLE_NAME    
VALUES (value1, value2, value3, .... valueN);    

For example:

INSERT INTO students (RollNo, FIrstName, LastName) VALUES ('60', 'Tom', Erichsen');

UPDATE:

This command is used to update or modify the value of a column in the table.

Syntax:

UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE CONDITION]   

For example:

UPDATE students    
SET FirstName = 'Jhon', LastName= 'Wick' 
WHERE StudID = 3;

DELETE:

This command is used to remove one or more rows from a table.

Syntax:

DELETE FROM table_name [WHERE condition];  

For example:

DELETE FROM students 
WHERE FirstName = 'Jhon';

What is DCL?

DCL (Data Control Language) includes commands like GRANT and REVOKE, which are useful to give “rights & permissions.” Other permission controls parameters of the database system.

Examples of DCL commands:

Commands that come under DCL:

  • Grant
  • Revoke

Grant:

This command is use to give user access privileges to a database.

Syntax:

GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;  

For example:

GRANT SELECT ON Users TO'Tom'@'localhost;

Revoke:

It is useful to back permissions from the user.

Syntax:

REVOKE privilege_nameON object_nameFROM {user_name |PUBLIC |role_name}

For example:

REVOKE SELECT, UPDATE ON student FROM BCA, MCA;  

What is TCL?

Transaction control language or TCL commands deal with the transaction within the database.https://512407338df7b501d08d199e3f6a225b.safeframe.googlesyndication.com/safeframe/1-0-38/html/container.html

Commit

This command is used to save all the transactions to the database.

Syntax:

Commit;

For example:

DELETE FROM Students  
WHERE RollNo =25;  
COMMIT;  

Rollback

Rollback command allows you to undo transactions that have not already been saved to the database.

Syntax:

ROLLBACK;  

Example:

DELETE FROM Students  
WHERE RollNo =25;  

SAVEPOINT

This command helps you to sets a savepoint within a transaction.

Syntax:

SAVEPOINT SAVEPOINT_NAME;

Example:

SAVEPOINT RollNo;

What is DQL?

Data Query Language (DQL) is used to fetch the data from the database. It uses only one command:

SELECT:

This command helps you to select the attribute based on the condition described by the WHERE clause.

Syntax:

SELECT expressions    
FROM TABLES    
WHERE conditions;  

For example:

SELECT FirstName  
FROM Student  
WHERE RollNo > 15;  

Summary:

  • SQL is a database language designed for the retrieval and management of data in a relational database.
  • It helps users to access data in the RDBMS system
  • In the year 1974, the term Structured Query Language appeared
  • Five types of SQL queries are 1) Data Definition Language (DDL) 2) Data Manipulation Language (DML) 3) Data Control Language(DCL) 4) Transaction Control Language(TCL) and, 5) Data Query Language (DQL)
  • Data Definition Language(DDL) helps you to define the database structure or schema.
  • Data Manipulation Language (DML) allows you to modify the database instance by inserting, modifying, and deleting its data.
  • DCL (Data Control Language) includes commands like GRANT and REVOKE, which are useful to give “rights & permissions.”
  • Transaction control language or TCL commands deal with the transaction within the database.
  • Data Query Language (DQL) is used to fetch the data from the database.

WHAT IS QUERY WEB SERVICE FROM SQL SERVER?

Web service queries

Query services that are created in the Enterprise Services application and the Object Structures applications can be deployed as web services. To support querying, you must configure enterprise web services to bypass the JMS queues.

A successful response to a query that is run in a web service returns the query result set. If the result set is empty (it contains no records), the XML that is returned in the SOAP body contains the following empty MXPERSONSet tag:

<max:QueryMXPERSONResponse xmlns:max="http://www.ibm.com/maximo" 
  creationDateTime="2011-04-28T21:49:45" 
  baseLanguage="EN" transLanguage="EN" messageID="12345" 
  maximoVersion="7.5" rsStart="1" rsCount="10" rsTotal="10">
  </max:MXPERSONSet> 
</max:QueryMXPERSONResponse>

If an error occurs, an HTTP response code of 500 is returned, along with a SOAP fault detailing the error message.

Use the following URL for the query web service:

http://hostname:port/meaweb/services/web service name
  • The host:port/meaweb is the value of the integration web application URL property.
  • The web service name is the name of the web service.

You deploy query enterprise and object structure services as web services using the Web Services Library application.

How To Call A Web Service From SQL Server

Step 1 Create a stored procedure in your SQL Server.

  1. CREATE proc [dbo].[spHTTPRequest]     
  2.       @URI varchar(2000) = ‘http://localhost:55253/’,          
  3.       @methodName varchar(50) = ‘Get’,     
  4.       @requestBody varchar(8000) = ”,     
  5.       @SoapAction varchar(255),     
  6.       @UserName nvarchar(100), — Domain\UserName or UserName     
  7.       @Password nvarchar(100),     
  8.       @responseText varchar(8000) output    
  9. as    
  10. SET NOCOUNT ON    
  11. IF    @methodName = ”    
  12. BEGIN    
  13.       select FailPoint = ‘Method Name must be set’    
  14.       return    
  15. END    
  16. set   @responseText = ‘FAILED’    
  17. DECLARE @objectID int    
  18. DECLARE @hResult int    
  19. DECLARE @source varchar(255), @desc varchar(255)     
  20. EXEC @hResult = sp_OACreate ‘MSXML2.ServerXMLHTTP’, @objectID OUT    
  21. IF @hResult <> 0     
  22. BEGIN    
  23.       EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT    
  24.       SELECT      hResult = convert(varbinary(4), @hResult),     
  25.                   source = @source,     
  26.                   description = @desc,     
  27.                   FailPoint = ‘Create failed’,     
  28.                   MedthodName = @methodName     
  29.       goto destroy     
  30.       return    
  31. END    
  32. — open the destination URI with Specified method     
  33. EXEC @hResult = sp_OAMethod @objectID, ‘open’, null, @methodName, @URI, ‘false’, @UserName, @Password    
  34. IF @hResult <> 0     
  35. BEGIN    
  36.       EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT    
  37.       SELECT      hResult = convert(varbinary(4), @hResult),     
  38.             source = @source,     
  39.             description = @desc,     
  40.             FailPoint = ‘Open failed’,     
  41.             MedthodName = @methodName     
  42.       goto destroy     
  43.       return    
  44. END    
  45. — set request headers     
  46. EXEC @hResult = sp_OAMethod @objectID, ‘setRequestHeader’, null, ‘Content-Type’, ‘text/xml;charset=UTF-8’    
  47. IF @hResult <> 0     
  48. BEGIN    
  49.       EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT    
  50.       SELECT      hResult = convert(varbinary(4), @hResult),     
  51.             source = @source,     
  52.             description = @desc,     
  53.             FailPoint = ‘SetRequestHeader failed’,     
  54.             MedthodName = @methodName     
  55.       goto destroy     
  56.       return    
  57. END    
  58. — set soap action     
  59. EXEC @hResult = sp_OAMethod @objectID, ‘setRequestHeader’, null, ‘SOAPAction’, @SoapAction     
  60. IF @hResult <> 0     
  61. BEGIN    
  62.       EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT    
  63.       SELECT      hResult = convert(varbinary(4), @hResult),     
  64.             source = @source,     
  65.             description = @desc,     
  66.             FailPoint = ‘SetRequestHeader failed’,     
  67.             MedthodName = @methodName     
  68.       goto destroy     
  69.       return    
  70. END    
  71. declare @len int    
  72. set @len = len(@requestBody)     
  73. EXEC @hResult = sp_OAMethod @objectID, ‘setRequestHeader’, null, ‘Content-Length’, @len     
  74. IF @hResult <> 0     
  75. BEGIN    
  76.       EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT    
  77.       SELECT      hResult = convert(varbinary(4), @hResult),     
  78.             source = @source,     
  79.             description = @desc,     
  80.             FailPoint = ‘SetRequestHeader failed’,     
  81.             MedthodName = @methodName     
  82.       goto destroy     
  83.       return    
  84. END    
  85. /*    
  86. — if you have headers in a table called RequestHeader you can go through them with this    
  87. DECLARE @HeaderKey varchar(500), @HeaderValue varchar(500)    
  88. DECLARE RequestHeader CURSOR   
  89. LOCAL FAST_FORWARD    
  90. FOR   
  91.       SELECT      HeaderKey, HeaderValue    
  92.       FROM RequestHeaders    
  93.       WHERE       Method = @methodName    
  94. OPEN RequestHeader    
  95. FETCH NEXT FROM RequestHeader    
  96. INTO @HeaderKey, @HeaderValue    
  97. WHILE @@FETCH_STATUS = 0    
  98. BEGIN   
  99.       –select @HeaderKey, @HeaderValue, @methodName    
  100.       EXEC @hResult = sp_OAMethod @objectID, ‘setRequestHeader’, null, @HeaderKey, @HeaderValue    
  101.       IF @hResult <> 0    
  102.       BEGIN   
  103.             EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT   
  104.             SELECT      hResult = convert(varbinary(4), @hResult),    
  105.                   source = @source,    
  106.                   description = @desc,    
  107.                   FailPoint = ‘SetRequestHeader failed’,    
  108.                   MedthodName = @methodName    
  109.             goto destroy    
  110.             return   
  111.       END   
  112.       FETCH NEXT FROM RequestHeader    
  113.       INTO @HeaderKey, @HeaderValue    
  114. END   
  115. CLOSE RequestHeader    
  116. DEALLOCATE RequestHeader    
  117. */     
  118. — send the request     
  119. EXEC @hResult = sp_OAMethod @objectID, ‘send’, null, @requestBody     
  120. IF    @hResult <> 0     
  121. BEGIN    
  122.       EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT    
  123.       SELECT      hResult = convert(varbinary(4), @hResult),     
  124.             source = @source,     
  125.             description = @desc,     
  126.             FailPoint = ‘Send failed’,     
  127.             MedthodName = @methodName     
  128.       goto destroy     
  129.       return    
  130. END    
  131. declare @statusText varchar(1000), @status varchar(1000)     
  132. — Get status text     
  133. exec sp_OAGetProperty @objectID, ‘StatusText’, @statusText out    
  134. exec sp_OAGetProperty @objectID, ‘Status’, @status out    
  135. select @status, @statusText, @methodName     
  136. — Get response text     
  137. exec sp_OAGetProperty @objectID, ‘responseText’, @responseText out    
  138. IF @hResult <> 0     
  139. BEGIN    
  140.       EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT    
  141.       SELECT      hResult = convert(varbinary(4), @hResult),     
  142.             source = @source,     
  143.             description = @desc,     
  144.             FailPoint = ‘ResponseText failed’,     
  145.             MedthodName = @methodName     
  146.       goto destroy     
  147.       return    
  148. END    
  149. destroy:     
  150.       exec sp_OADestroy @objectID     
  151. SET NOCOUNT OFF    
  152.      
  153. GO    

The Stored Procedure takes the following parameters.

  1. @URI: the URI of the web service
  2. @MethodName: this would be ‘GET’ or ‘POST’
  3. @RequestBody: this is the SOAP xml that you want to send
  4. @SoapAction: this the operation that you want to call on your service
  5. @UserName: NT UserName if your web service requires authentication
  6. @Password: the password if using NT Authentication on the web service
  7. @ResponseText: this is an out parameter that contains the response from the web service

Step 2 Make the setting in SQL for it.

  1. Use master  
  2. sp_configure ‘show advanced options’, 1   
  3.   
  4. GO   
  5. RECONFIGURE;   
  6. GO   
  7. sp_configure ‘Ole Automation Procedures’, 1   
  8. GO   
  9. RECONFIGURE;   
  10. GO   
  11. sp_configure ‘show advanced options’, 1   
  12. GO   
  13. RECONFIGURE;  

Step 3

Call the stored procedure (Here is a sample call to my service).

  1. declare @xmlOut varchar(8000)  
  2. Declare @RequestText as varchar(8000);  
  3. set @RequestText=  
  4. ‘<soapenv:Envelope xmlns:soapenv=”http://schemas.xmlsoap.org/soap/envelope/” xmlns:tem=”http://tempuri.org/”>  
  5.    <soapenv:Header/>  
  6.    <soapenv:Body>  
  7.       <tem:CreateOrder>  
  8.          <!–Optional:–>  
  9.          <tem:OrderRequest>  
  10.             <tem:OrderId>200</tem:OrderId>  
  11.             <!–Optional:–>  
  12.             <tem:OrderName>something</tem:OrderName>  
  13.          </tem:OrderRequest>  
  14.       </tem:CreateOrder>  
  15.    </soapenv:Body>  
  16. </soapenv:Envelope>’  
  17. exec spHTTPRequest  
  18. ‘http://localhost/testwebservices/helloworldservice.asmx’,  
  19. ‘POST’,  
  20. @RequestText,  
  21. ‘http://tempuri.org/CreateOrderForMe’,   — this is your SOAPAction:  
  22. ”, ”, @xmlOut out  
  23. select @xmlOut   

Advantages of Web Service

The thought of web services created from the development of the Internet. The plan behind a web service is to drive the internet as a value-based instrument as opposed to just a visual apparatus. These application-to-application collaborations are driven by, and based on, existing principles, for example:

  • Extensible Markup Language (XML)
  • Hypertext Transfer Protocol (HTTP)
  • Cleanser
  • Widespread Description, Discovery, and Integration (UDDI)
  • Web Services Description Language (WSDL)

Here are the advantages of utilizing web services are:

1. Revealing the Existing Function on Framework

A web administration is a managed code that can be remotely called using HTTP; that is, it tends to be started using HTTP inquiries. Web administrations empower you to uncover the handiness of your present code over the framework. At the point when it is uncovered on the framework, other applications can use the handiness of your program. 

2. Interoperability

Web service interoperability objectives are to give consistent and programmed associations starting with one programming application then onto the next. Cleanser, WSDL, and UDDI conventions characterize a self-depicting approach to find and call a product application strategy – paying little mind to area or stage. Information is marshaled into XML solicitation and reaction reports and moved between programming bundles utilizing HTTP or message-based conventions. Interoperability issues creep in at the disclosure, definition, and solicitation/reaction instruments.

  • Web administrations empower various applications to banter with one another and share information and administrations among themselves. A wide range of uses can converse with one another. So as opposed to composing explicit code that explicit applications must comprehend, you would now be able to compose nonexclusive code that all applications can comprehend.
  • When looked with a test changing frameworks designs, heritage frameworks, a mixed drink of programming dialects that make up frameworks that should be coordinated at that point, web administrations prove to be useful.
  • Maybe the most significant advantage of web administrations they give a nonexclusive method for cooperation. Web benefits just need to talk a similar message convention for them to between work. So far, a typical arrangement of norms based specialized techniques that incorporate HTTP, WSDL, SOAP have been created. These make it feasible for web administrations to be stage free.

3. Ordered Protocol

Web administrations use the institutionalized industry-standard show for the correspondence. All the four layers (Service Transport, XML Messaging, Service Description, and Service Discovery layers) use well-described shows in the web organizations show stack. This systematization of show stack gives the business various focal points, for instance, a wide extent of choices, a decline in the cost due to contention, and augmentation in the quality.

4. Ease of Use

Web services are intended to be utilized over the web; that is simply similarly a page is brought, one can get web administration capacity over the web. The ability of web administrations shifts from straightforward data query too complex algorithmic calculations. Thusly when help is utilized to uncover a business rationale, at that point, it can be used without much of a stretch utilized.

5.Send Capacity

Web Services are conveyed over standard Internet advancements. For example, utilizing Apache, Axis2 to give HTTP, WSDL driven administrations. This makes it easy to convey.

6. Agility

This sees the capacity to change. At the point when an undertaking IT framework is streamlined into administrations, new usefulness to address new business requests involves amassing existing administrations. Obviously, a couple of more administrations may need to manufacture, yet in general, it is simpler than re-assembling another framework without any preparation.

7. Quality

Related to reuse, on the grounds that web services advancement approaches enable administrations to be worked by gathering existing administrations, it is consistent to expect that such administrations are now tried with known execution attributes. Consequently, new frameworks will be less carriage.

8. Cost

The expense of growing new frameworks diminishes altogether since such frameworks are amassed from instant web administrations. Such cost decreases convert into benefits on might be passed on to the clients. The clients remain to win from cost cuts, and proficiency got by web administration.

9. Minimal Effort Communication(XML-Based)

Web Services uses XML at data depiction and data transportation layers. Using XML  gets rid of any frameworks organization, working system, or stage official. Web Services based applications are significantly between operable application at their inside level.

Conclusion

Ideally, this article has given you an understanding of Web administrations’ capability, especially for settling a ton of the cross-stage availability issues that software engineers and framework creators. Making a Web service includes huge numbers of similar ideas and errands we face when fabricating any sort of application. We characterize the usefulness and logic necessary to create the service.

Drop your comment

Hits: 5

Related Post

Leave a Reply

Your email address will not be published.