mysql2011. 8. 29. 02:45


이렇게 mysql 을 접속하면 에러가 뜬다 
비밀번호없이 공백을 입력해도 비밀번호를 입력해도 

해결방안

 
2번까지로 들어가는것이 비밀번호 초기화 하는것이다 
저렇게 3번까지 한후에

-   mysql>use mysql

-   mysql>update user set password=password('새암호') where user='root';

-   mysql> FLUSH PRIVILEGES;

-   mysql> exit

마지막 mysql -uroot -p비밀번호 or mysql -uroot -p 후 비밀번호 하는것

둘중 하나 선택하면 됩니다 
Posted by babuzzzy
mysql2011. 8. 29. 02:29
use sqlDB

create table categories
(
categoryID int identity(1,1) not null primary key,--카테고리 번호
categoryName varchar(25) not null   --카테고리 이름
)
go

insert categories values('가전')
insert categories values('컴퓨터')
insert categories values('서적')

create table products
(
productID int identity(1,1) not null primary key,-- 제품고유번호
modelName varchar(25) not null, -- 상품명
sellPrice int null, --판매가격
categoryID int null -- 카테고리(1,2,3)
)
go
insert products values('냉장고',100, 1)
insert products values('노트북',200, 2)
insert products values('데스크탑',150, 3)

select * from products
select * from categories

--SQL SERVER 조인구문

select modelName, sellPrice, categoryName
from products, categories
where products.categoryID = categories.categoryID

--SQL 조인구문
select products.modelName, products.sellPrice, categories.categoryName
from products join categories 
on products.categoryID = categories.categoryID

select 열이름
from 첫번째테이블 join 두번째테이블
on 조건절

--조인구문 상세
select *
from inner join
on
go

select products.modelName, products.sellPrice, categories.categoryName
from products inner join categories 
on products.categoryID = categories.categoryID

select p.modelName, p.sellPrice, c.categoryName
from products p join categories c
on p.categoryID = c.categoryID


-- 서브쿼리를 사용한 조인
select modelName, sellprice, categoryID
from products
where categoryID in(select categoryID from categories)

--inner join(내부조인)
-- 
select <열목록>
from <첫번째테이블>
inner join <두번째테이블>
on <조인이 될 조건>
where 검색 조건

select * from usertbl
select * from buytbl
--sql join
select * 
from buytbl
inner join usertbl
on buytbl.userid = usertbl.userid
where buytbl.userid = 'LCS'

--sql server 
select * 
from buytbl, usertbl
where buytbl.userid = usertbl.userid

-- 상세 조인구문

select num, buytbl.userid, prodName, amount, addr
from buytbl
inner join usertbl
on buytbl.userid = usertbl.userid
where buytbl.userid = 'LCS'
Posted by babuzzzy
mysql2011. 8. 29. 02:28
use tempDB

create table maxTbl
(col1 varchar(max),
col2 nvarchar(max))

insert into maxTbl values(replicate('A',1000000),
replicate('가',1000000))


select * from maxtbl

select len(col1) as [varchar(max)],len(col2) as [nvarchar(max)]
from maxtbl


-- 순위 함수 row_number()

use sqlDB
select row_number() over(order by height desc) [키큰 순위],
name, addr, height
from usertbl
order by height desc
Posted by babuzzzy
mysql2011. 8. 29. 02:28
use master

create database sqlDB
go

use sqlDB

CREATE TABLE userTbl -- 사용자테이블
( userID  nchar(8) NOT NULL PRIMARY KEY, -- 사용자아이디
  name    nvarchar(10) NOT NULL, -- 이름
  birthYear   int NOT NULL,  -- 출생년도
  addr  nchar(4) NOT NULL, -- 지역(경기,서울,경남,전북식으로2글자만입력)
  mobile1 nchar(3), -- 휴대폰의국번(011, 016, 017, 018, 019, 010 등)
  mobile2   nchar(8), -- 휴대폰의나머지전화번호(하이픈제외)
height    smallint  -- 신장
)
GO

CREATE TABLE buyTbl -- 사용자구매테이블
(  num int IDENTITY NOT NULL PRIMARY KEY, -- 순번(PK)
   userid  nchar(8) NOT NULL --아이디(FK)
FOREIGN KEY REFERENCES userTbl(userid),
   prodName nchar(6) NOT NULL, -- 물품명
   groupName nchar(4)  , -- 분류
   price     int  NOT NULL, -- 단가
   amount    smallint  NOT NULL -- 수량
)
GO

INSERT INTO userTbl VALUES(N'PJS', N'박지성', 1983, N'서울', N'011', N'1111111', 181)
INSERT INTO userTbl VALUES(N'PJY', N'박주영', 1986, N'경기', N'011', N'2222222', 178)
INSERT INTO userTbl VALUES(N'JJJ', N'조재진', 1986, N'충북', N'019', N'3333333', 179)
INSERT INTO userTbl VALUES(N'LCS', N'이천수', 1983, N'인천', N'011', N'4444444', 179)
INSERT INTO userTbl VALUES(N'AJH', N'안정환', 1979, N'강원', NULL  , NULL      , 182)
INSERT INTO userTbl VALUES(N'KNI', N'김남일', 1977, N'경북', N'016', N'6666666', 183)
INSERT INTO userTbl VALUES(N'LYP', N'이영표', 1983, N'전북', NULL  , NULL      , 178)
INSERT INTO userTbl VALUES(N'SKH', N'설기현', 1978, N'서울', N'011', N'8888888', 182)
INSERT INTO userTbl VALUES(N'SJK', N'송종국', 1979, N'경기', N'018', N'9999999', 178)
INSERT INTO userTbl VALUES(N'CJC', N'최진철', 1975, N'제주', N'019', N'0000000', 185)
GO

INSERT INTO buyTbl VALUES(N'PJY', N'운동화', NULL   , 30,   2)
INSERT INTO buyTbl VALUES(N'PJY', N'노트북', N'전자', 1000, 1)
INSERT INTO buyTbl VALUES(N'LCS', N'모니터', N'전자', 200,  1)
INSERT INTO buyTbl VALUES(N'CJC', N'모니터', N'전자', 200,  5)
INSERT INTO buyTbl VALUES(N'PJY', N'청바지', N'의류', 50,   3)
INSERT INTO buyTbl VALUES(N'CJC', N'메모리', N'전자', 80,  10)
INSERT INTO buyTbl VALUES(N'AJH', N'책'    , N'서적', 15,   5)
INSERT INTO buyTbl VALUES(N'SKH', N'책'    , N'서적', 15,   2)
INSERT INTO buyTbl VALUES(N'SKH', N'청바지', N'의류', 50,   1)
INSERT INTO buyTbl VALUES(N'CJC', N'운동화', NULL   , 30,   2)
INSERT INTO buyTbl VALUES(N'SKH', N'책'    , N'서적', 15,   1)
INSERT INTO buyTbl VALUES(N'CJC', N'운동화', NULL   , 30,   2)
GO

select * from userTbl
go

select * from dbo.buyTbl
go

select name, birthyear, addr from dbo.userTbl 
where name='박지성'

select * from SQLEXPRESS.sqlDB.dbo.userTbl 
where birthyear > 1980 and height >180

--1980년 이후에 출생을 했거나, 
--신장이 180이상인 사람의 아이디와 이름을 조회

select userid, name from userTbl 
where birthyear > 1980 or height >= 180

--키가 180~ 183 사이인 사람에 아이디와 이름
select userid, name from usertbl
where height >=180 and height <= 183

select userid, name from usertbl 
where height between 180 and 183

--키가 정확하게 178인사람 또는 180인 사람 또는 182인 사람
select userid, name,height from usertbl
where height = 178 or height = 180 or height = 182

select userid, name, height from usertbl
where height in(178, 180, 182)

use sqlDB

-- 박지성보다 키가큰 사람의 이름과 키를 출력해보자

select * from usertbl where height > 181

select name, height from usertbl where height >
(select height from usertbl where name='박지성')


-- 휴대폰 국번이 019인 사람의 키보다, 키가 크거나 같은 사람을 출력

select height from usertbl



select name, height from usertbl
where height >= (select height from usertbl where mobile1='019')

select name, height from usertbl where mobile1='019'
-- any 서브쿼리 여러개의 결과중에 한가지만 만족하더라도 결과 출력
select name, height from usertbl
where height >= any(select height from usertbl where mobile1='019')

-- all 서브쿼리 여러개의 결과를 모두 만족해야 결과를 출력
select name, height from usertbl
where height >= all(select height from usertbl where mobile1='019')


--ORDER BY DESC//ORDER BY ASC

select * from buyTbl order by num desc
select * from buyTbl order by num asc
select * from buyTbl
select * from buytbl order by price asc

-- 회원 거주지 주소를 출력해보자



select addr from usertbl 

select addr from usertbl order by addr

-- 중복요소 제거 DISTINCT

select distinct addr from usertbl order by addr


select top(5) * from usertbl



use master

exec sp_attach_db @dbname=N'AdventureWorks', 
@filename1=N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\AdventureWorks_Data.mdf', 
@filename2=N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\AdventureWorks_log.ldf'






use AdventureWorks

select * from Sales.CreditCard


select top(select count(*)/100 from Sales.CreditCard) CreditCardID 
from Sales.CreditCard
where CardType = 'Vista'
order by ExpYear, ExpMonth

select count(*)/100 from Sales.CreditCard



select top(1)percent CreditCardID from Sales.CreditCard
where CardType = 'Vista'
order by ExpYear, ExpMonth

select count(*)/100 from Sales.CreditCard

use sqlDB

select top(1) * from usertbl


--select into

--SELECT 복사할열 INTO 새로운 테이블 FROM 기존테이블

select * into usertbl2 from usertbl


--* GROUP BY 및 HAVING 그리고 집계함수

select userid, amount from buytbl order by userid

-- AJH 5, CJC 19, LCS 1, PJY 6, SKH 4

select userid, sum(amount) from buytbl group by userid

-- 별칭을 사용해본다.
select userid as [사용자 아이디], 
SUM(amount) AS [총 구매 개수]
from buytbl group by userid


--집계함수 AVG() : 평균을 구한다
--MIN() : 최소값을 구한다
--MAX() : 최대값을 구한다
--COUNT() : 행의 개수를 센다

SELECT AVG(amount) as [평균구매개수] from buytbl
select * from buytbl

--25/12

--having
select userid as [사용자], sum(price*amount) as [총구매금액]
from buytbl
group by userid
having sum(price*amount)>1000

-- compute, compute by, rollup, cube, grouping() 함수
-- select 결과에 대한 요약의 형태를 보여주는 구문

select *, price*amount as[가격] from buytbl
compute sum(price * amount)
compute avg(price * amount)

select *, price*amount as[가격] from buytbl
order by groupName
compute sum(price * amount) by groupName
compute avg(price * amount) by groupName

select * from buytbl


select num, groupName, sum(price * amount) as [비용]
from buytbl
group by groupName, num
with rollup

select groupName, sum(price * amount) as [비용]
, grouping(groupName) as [추가행여부]
from buytbl
group by groupName
with rollup
Posted by babuzzzy
mysql2011. 8. 29. 02:26
create table dbo.Memos
(
Num int identity(1,1) Not Null primary key, -- 번호
Name varchar(30) Not Null, --이름
Email varchar(30) Null, --이메일
Title varchar(30) Not Null, --제목(간단한 내용)
PostDate datetime Default(getdate()), --작성일
PostIp varchar(30) Null
)
go
Posted by babuzzzy
mysql2011. 8. 29. 02:25
use master  

create database sqlDB

go

use sqlDB


USE sqlDB
CREATE TABLE userTbl -- 사용자테이블
( userID  nchar(8) NOT NULL PRIMARY KEY, -- 사용자아이디
  name    nvarchar(10) NOT NULL, -- 이름
  birthYear   int NOT NULL,  -- 출생년도
  addr  nchar(4) NOT NULL, -- 지역(경기,서울,경남,전북식으로2글자만입력)
  mobile1 nchar(3), -- 휴대폰의국번(011, 016, 017, 018, 019, 010 등)
  mobile2   nchar(8), -- 휴대폰의나머지전화번호(하이픈제외)
height    smallint  -- 신장
)
GO
CREATE TABLE buyTbl -- 사용자구매테이블
(  num int IDENTITY NOT NULL PRIMARY KEY, -- 순번(PK)
   userid  nchar(8) NOT NULL --아이디(FK)
FOREIGN KEY REFERENCES userTbl(userid),
   prodName nchar(6) NOT NULL, -- 물품명
   groupName nchar(4)  , -- 분류
   price     int  NOT NULL, -- 단가
   amount    smallint  NOT NULL -- 수량
)
GO

INSERT INTO userTbl VALUES(N'PJS', N'박지성', 1983, N'서울', N'011', N'1111111', 181)
INSERT INTO userTbl VALUES(N'PJY', N'박주영', 1986, N'경기', N'011', N'2222222', 178)
INSERT INTO userTbl VALUES(N'JJJ', N'조재진', 1986, N'충북', N'019', N'3333333', 179)
INSERT INTO userTbl VALUES(N'LCS', N'이천수', 1983, N'인천', N'011', N'4444444', 179)
INSERT INTO userTbl VALUES(N'AJH', N'안정환', 1979, N'강원', NULL  , NULL      , 182)
INSERT INTO userTbl VALUES(N'KNI', N'김남일', 1977, N'경북', N'016', N'6666666', 183)
INSERT INTO userTbl VALUES(N'LYP', N'이영표', 1983, N'전북', NULL  , NULL      , 178)
INSERT INTO userTbl VALUES(N'SKH', N'설기현', 1978, N'서울', N'011', N'8888888', 182)
INSERT INTO userTbl VALUES(N'SJK', N'송종국', 1979, N'경기', N'018', N'9999999', 178)
INSERT INTO userTbl VALUES(N'CJC', N'최진철', 1975, N'제주', N'019', N'0000000', 185)
GO

INSERT INTO buyTbl VALUES(N'PJY', N'운동화', NULL   , 30,   2)
INSERT INTO buyTbl VALUES(N'PJY', N'노트북', N'전자', 1000, 1)
INSERT INTO buyTbl VALUES(N'LCS', N'모니터', N'전자', 200,  1)
INSERT INTO buyTbl VALUES(N'CJC', N'모니터', N'전자', 200,  5)
INSERT INTO buyTbl VALUES(N'PJY', N'청바지', N'의류', 50,   3)
INSERT INTO buyTbl VALUES(N'CJC', N'메모리', N'전자', 80,  10)
INSERT INTO buyTbl VALUES(N'AJH', N'책'    , N'서적', 15,   5)
INSERT INTO buyTbl VALUES(N'SKH', N'책'    , N'서적', 15,   2)
INSERT INTO buyTbl VALUES(N'SKH', N'청바지', N'의류', 50,   1)
INSERT INTO buyTbl VALUES(N'CJC', N'운동화', NULL   , 30,   2)
INSERT INTO buyTbl VALUES(N'SKH', N'책'    , N'서적', 15,   1)
INSERT INTO buyTbl VALUES(N'CJC', N'운동화', NULL   , 30,   2)
GO

SELECT * FROM userTbl
SELECT * FROM buyTbl

----------- 여기까지가  테이블 만들고 정보 입력하는거이다

USE master
BACKUP DATABASE sqlDB TO DISK = 'C:\sqlDB.bak'

SELECT * FROM userTbl

SELECT * FROM userTbl WHERE name = '박지성'

SELECT userID, Name FROM userTbl WHERE birthYear >= 1981 AND height >= 180

SELECT userID, Name FROM userTbl WHERE birthYear >= 1981 OR height >= 180

SELECT Name, height FROM userTbl WHERE height >= 180 AND height <= 183

SELECT Name, height FROM userTbl WHERE height BETWEEN 180 AND 183

SELECT Name, height FROM userTbl WHERE height=178 OR height=180 OR height=182

SELECT Name, height FROM userTbl WHERE height IN (178, 180, 182)

SELECT Name, height FROM userTBL WHERE height > 181

SELECT Name, height FROM userTbl 
  WHERE height > (SELECT height FROM userTbl WHERE Name = '박지성')

SELECT Name, height FROM userTbl 
  WHERE height >= (SELECT height FROM userTbl WHERE mobile1 = '019')

SELECT Name, height FROM userTbl 
  WHERE height >= ANY (SELECT height FROM userTbl WHERE mobile1 = '019')

SELECT Name, height FROM userTbl 
  WHERE height = ANY (SELECT height FROM userTbl WHERE mobile1 = '019')

SELECT Name, height FROM userTbl 
  WHERE height IN (SELECT height FROM userTbl WHERE mobile1 = '019')

SELECT Name, height FROM userTbl ORDER BY height

SELECT Name, height FROM userTbl ORDER BY height DESC

SELECT Name, height FROM userTbl ORDER BY height DESC, name ASC

SELECT addr FROM userTbl

SELECT addr FROM userTbl ORDER BY addr

SELECT DISTINCT addr FROM userTbl



USE sqlDB
SELECT * INTO buyTbl2 FROM buyTbl
SELECT * FROM buyTbl2

SELECT userid, prodName INTO buyTbl3 FROM buyTbl
SELECT * FROM buyTbl3


USE sqlDB
SELECT userid, price, amount FROM buyTbl ORDER BY userid

SELECT userid, SUM(amount)  FROM buyTbl GROUP BY userid

SELECT userid AS [사용자아이디], SUM(amount) AS [총구매개수]  
  FROM buyTbl GROUP BY userid

SELECT userid AS [사용자아이디], SUM(price*amount) AS [총구매액]  
  FROM buyTbl GROUP BY userid

SELECT AVG(amount) AS [평균구매개수] FROM buyTbl

SELECT AVG(amount*1.0) AS [평균구매개수] FROM buyTbl
  -- 또는
SELECT AVG(CAST(amount AS DECIMAL(10,6))) AS [평균구매개수] FROM buyTbl

SELECT userid, AVG(amount*1.0) AS [평균구매개수] FROM buyTbl
  GROUP BY userid

SELECT Name, MAX(height), MIN(height) FROM userTbl

SELECT Name, MAX(height), MIN(height) FROM userTbl GROUP BY Name

SELECT Name, height
FROM userTbl 
WHERE height = (SELECT MAX(height)FROM userTbl) 
   OR height = (SELECT MIN(height)FROM userTbl)

SELECT COUNT(*) FROM userTbl

SELECT COUNT(mobile1) FROM userTbl

--------------다양한 방법으로 selec 문을 실행


 
Posted by babuzzzy
mysql2011. 8. 29. 02:21
--GROUP BY  및 HAVING 그리고 집계함수

select userid, amount from buytbl order by userid



--합계
select userid, sum(amount) from buytbl group by userid


--병칭을 사용해준다
select userid as [사용자 아이디],
SUM(amount) AS [총 구매 개수]
from buytbl group by userid

--select 복사할열 into 새로운 테이블 from 기존테이블

select  * into usertbl2 from memos

-- group by 및 HAVING 그리고 집계함수

select userid, amount from table_2 order by userid


--count () : 행의 개수를 센다
SELECT AVG(amount) as [평균 구매개수] from buytbl
select * from buytbl

--25/12

--having  --웨어절 에 함수를 쓰고 싶을때  
select userid as [사용자], sum(price *amount) as [총 구매 금지]
from buytbl
group by userid 
having sum(price *amount) >1000


----------------------------------------
use master

exec sp_attach_db @dbname=N'AdventureWorks', 
@filename1=N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\AdventureWorks_Data.mdf', 
@filename2=N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\AdventureWorks_log.ldf'


use AdventureWorks

select top(select count(*)/100 from Sales.CreditCard) CreditCardID from Sales.CreditCard
where CardType = 'Vista'
order by ExpYear, ExpMonth


select top(0.1)percent CreditCardID from Sales.CreditCard
where CardType = 'Vista'
order by ExpYear, ExpMonth

-- select count(*)/100 from Sales.CreditCard

use sqldb
use mydatabase


select * from memos

--select 복사할열 into 새로운 테이블 from 기존테이블

select  * into usertbl2 from memos

-- group by 및 HAVING 그리고 집계함수

select userid, amount from table_2 order by userid
----------------------------
Posted by babuzzzy
mysql2011. 8. 29. 02:21

--  튜플 추가하는 프로시저
create proc dbo.addmemo1
(                  
@name varchar(30),
@email varchar(30),
@title varchar(30),
@postip varchar(30)
)
as
insert table1(name,email,title,postdate,postip)     
values(@name,@email,@title,getdate(),@postip)   

go

execute addmemo1 '노종현이죠','babuemf.naver.com' ,'난 최고죠' ,'123.213.123'
go


--[출력]
select * from table1
go

--num 값으로 값을 삭제하는 프로시저만들기

create proc dbo.delete1
(
@num int

)
as
delete table1 where num=@num
go

exec delete1 4
go
------------------------------------------
--num 값을이용해 원하는 튜플을 검색

create proc dbo.getmemo111
(
@num int
)
as                  

select num, name, title,postdate from table1 where num = @num
go

execute getmemo111 5
go  
----------------------------------------
--num값을 이용해서 튜플값 name과 email 값 수정
create proc dbo.editmemo1
(
@name varchar(20),
@email varchar(50),
@num int
)
as
begin tran

update dbo.table1
set name=@name,  email=@email         
where num=@num
commit tran
go

exec editmemo1 '보고싶다', '은수야', 2
go

-------------------------------------------

 -- select 로 함수로 이름검색하는 쿼리문을 
 -- 저장 프로시저로 변환  
select * from zzzz where name Like '%슥%'
go
   
------------------------------
--> 저장프로시저로 변형
create proc dbo.findmemos23
@searchfield varchar(50),
@searchquery varchar(50)         --이름으로 찾는거 

as  --name '+name+'

declare @strsql varchar (255)   --변수 정의
set @strsql='
select * from table1
where ' +@searchfield+' like ''%'+@searchquery+'%''
'
-- 왜 searchquery 에서 작은 따옴표를 두번써야하는가
exec (@strsql)
go

exec findmemos2 'name', '노'
go
--sql injection 발생 예제

exec findmemos1 '1=1;delete memos;--','홍길동'  -- sql 인젝션 

Posted by babuzzzy
mysql2011. 8. 29. 02:19
-- [입력] 저장 프로시저 만들기
create proc dbo.addtable1
(
@name varchar(30),
@email varchar(30), --변수 선언
@title varchar(30),
@postip varchar(30)
)
as
insert table1(name,email, title, postdate,postip)
values(@name,@email,@title, getdate(),@postip)
go

addtable1 '박은수','love@naver.com','보고싶었어','124.23.0.2'
go

addtable1 '박씨','comeon@nate.com','너란사람누굴까','123.5.3.2'
go


-- 프로시저써보기 - select 를 단축한 함수
create proc dbo.gettable1
as
select *
from table1
order by num desc

exec gettable1

-- 프로시저써보기 -  num변수 선언후 원하는 숫자 데이터만받기
create proc dbo.gettable4
(
@num int
)
as   

select num, name, title, postdate from table1 where num = @num
go

execute gettable4 6
go

Posted by babuzzzy
mysql2011. 8. 29. 02:19
-- T-SQL
-- SQL 문 내에서의 프로그램 문법 : 변수/연산자/제어문

-- 1~100 까지의 숫자중에 3의 배수 OR 4의 배수의 합을 



-- [1] 변수 선언
declare @i int
declare @sum int

-- [2] 변수의 초기화

set @sum = 0

-- [3] 반복문

set @i = 1      --초기값
while @i <= 100 --조건식
begin
if(@i % 3 =0) or (@i % 4 = 0)
begin
set @sum = @sum + @i
begin
set @sum = @sum + @i
end
set @i =@i+1  --증감식
end

select '1부터 100까지의 3의 배수, 4의 배수의 합:'
+cast(@sum as varchar)
go
Posted by babuzzzy