Showing posts with label syntax. Show all posts
Showing posts with label syntax. Show all posts

Thursday, 28 May 2015

copy tables with data from Current Database to another database in SQL Server Sytax

SCENARIO 
Suppose you have a table with some data in a Database A and you want to copy this data to a table in Database B .

then you should use the following syntax:

USE DatabaseB;

SELECT *
INTO NewTable
FROM DatabaseA.Schemaname.OldTable
Here NewTable and OldTable are two similar tables in different databases.
While handling different databases we must use fully qualified names
 to reach correct tables.





SQL Query COUNT() function syntax

SCENARIO 
Suppose you have a table, now you want to know the number of records in it. Then COUNT function will do the job.

SYNTAX of COUNT()

SELECT COUNT(ColumnName) from Table_NAME;

Suppose we have a table named Table_NAME
as
sql result image

Now if we run query     SELECT COUNT(ColumnName1) from Table_NAME;

Output = 4
 or if we run  SELECT COUNT(ColumnName3) from Table_NAME;

Output= 2
it means if we are running count on columns then it neglects the null value columns.

If you want to know the total number of records in a table then you can simply use
SELECT COUNT(*) from Table_NAME;

SQL Query Average function syntax

Scenario: Suppose you have a everyday sales table with you and you want to know the average sale happened on a day. Then using this function you can easily get this.

Syntax SELECT AVG(ColumnName) FROM table_name;

So lets suppose i have a 30 day sales data in the table named SALE. And there is a column SalesAmount which depicts the daily sale amount. and If we want to know the average sales happened in that month. We can easily get this using:

SELECT AVG(SalesAmount) FROM SALE;

SQL query Syntax Select all record from table

If you want to select everything from a table then use the follwing syntax:

SELECT * FROM table_name;

Here table_name is the name of the table of which you want to select the records.

This is basically see all record / data query.

How to create table in SQL Server Management Studio using SQL query

In SQL Server Management Studio, Althogh there are many ways to create a table using GUI and using query written in SQL.
So simple SQL Query to create a table

SQL CREATE TABLE Syntax

CREATE TABLE table_name
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....
);

for example: 
Create table Student(
StudentID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);