Click here to Skip to main content
15,879,535 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
i google internet for answer ,, but it's a little confusing ..

i have two query ...

1) select * from customer where cust_id=@id

2) select * from customer where cust_id=1


is (1) is dynamic sql statement and (2) is static sql statement

or dynamic is something other than this....

Pls respond ...
Thanx in advance
Posted

A Dynamic Sql Query is some thing that changes according to the user input.
Dynamic Queries can be executed using Execute(@SqlStmt) or exec(@SqlStmt) or sp_executesql
Check this below dynamic pivot for example..
SQL
Declare @Id varchar(4), @Sql varchar(400),@Cols varchar(40)
Create Table #Temp
		(
		Order_Id Int,
		InventoryId	 Int,
		ItemType Varchar(40),
		total Int
		)

Insert into #Temp
Values(1,5,'Orange',5000),(1,4,'Apple',3000),(2,1,'Mango',3400),(2,5,'Orange',1700)

Set @Id=2

Set @Cols= Stuff((Select Distinct '],['+ItemType From #Temp 
    Where Order_Id=@Id for Xml Path(''),Type).value('.','VARCHAR(Max)'), 1, 2,'')+']'

Set @Sql= 'Select '+@Cols + 'From (Select ItemType,total From #Temp 
    Where Order_Id= '+ @Id +')SourceTable pivot (Sum(total) For ItemType in ('
		   + @Cols + '))PivotTable'
Exec(@Sql)

Drop Table #Temp 

As the user changes the Id the Item Type picked for the pivot will be changed..
It will come in handy while using TableNames as variables etc...
 
Share this answer
 
Dynamic SQL is generally where the entire query is built at runtime.
So dynamic SQL would involve inserting the query into a variable then executing the variable as an SQL statement.
 
Share this answer
 

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