Use master
GO
Declare #dbName As VARCHAR(50)
SET #dbName = 'TestDB'
CREATE DATABASE #dbName
Above sqlserver is script is giving me error. Why?
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '#dbName'.
You can not use dynamic sql and ddl as mixed.
Use dynamic sql .
Try this code:
Use master
GO
Declare #dbName As VARCHAR(50)
DECLARE #Q VARCHAR(MAX)
SET #dbName = 'TestDB'
SET #Q='CREATE DATABASE '+ #dbName
EXEC(#Q)
If won't work because you're passing a VARCHAR type and for the creation of a database, it takes an object instead of a Varchar. Else, you'll need to pass the whole query as a string to execution;
Declare #dbName As VARCHAR(50) = 'TestDB'
DECLARE #Creation VARCHAR(50) ='CREATE DATABASE '+ #dbName
EXEC(#Creation)
Related
Requirement : We used to get min 10 to 50 table names (from different schema's and servers(using linked server ) as refresh requests from Prod to Test or Dev environment on regular basis.
Ex: We have 3 schema's called dbo,Schema1 and Schema 2 in prod where as in other environments we have different schema names such as schemaC and SchmaD etc.
For this I am using the below script to get the table names in single quotations.
Step 1 :
Declare #String Varchar(8000) = 'schemaname.table1,schemaname.table2,schemname.table1s45k'
Set #String = '''' + Replace(#String, ',', ''',''') + ''''
Select #String
Step 2 : I will backup the existing tables data in our bkpdata base table.
Step 3 : I will truncate the backedup tables
Step 4: I will move the data from Production to dev / test environment with help of linked server ex: in dev box
Insert into databasename.schemaname.tablename select * from linkedservername.schemaname.tablename
It would be great if we can get dynamic SQL code with parameters facility as Tablenames , databasename,linkedservername and schema name facility.
Any other options also highly appreciated.
adding additional details :
Declare #String Varchar(8000) = 'schema1.rnd,schema2.test'
Set #String = '''' + Replace(#String, ',', ''',''') + ''''
declare #Strings table (names varchar(max))
insert into #strings
select #String
select 'Truncate Table '+''+ name from sys.tables where name in (select name from #strings )
It will display the results as Truncate table Tablename . So I don't want to execute the results and it has to execute the output itself .I guess dynamic SQL Will help.
--#String contains location where to(db.schema.tablenm) copy and where from(servevr.dbb.schema.tablenm)
--At the end of each copy and copy from need to provide , as delimeter
--copy to and copy from is seprated by |
Declare #String Varchar(8000) =
'db.schema.tablenm|servevr.dbb.schema.tablenm,
db1.schema1.tablenm1|servevr1.db1.schema1.tablenm1,
db2.schema2.tablenm2|servevr2.db2.schema2.tablenm2,
'
Declare #str Varchar(8000)
Declare #execStr Varchar(8000)
Declare #delimeterocc int
Declare #delimeterSer int
declare #start int
set #start=0
Set #delimeterocc=charindex(',',#String)
While(#delimeterocc>0)
begin
set #str=SUBSTRING(#String,#start,len(#string)-(len(#String)-#delimeterocc)-#start)
Set #delimeterSer=charindex('|',#str)
print 'Insert Into ' + SUBSTRING(#str,1,#delimeterSer-1) + ' Select * From '+ SUBSTRING(#str,#delimeterSer+1,len(#str)-#delimeterSer)
Set #start=#delimeterocc+1
Set #delimeterocc=charindex(',',#String,#start)
end
I have about 12 tables in the database that are simple baseline data. As an example, I have Role and Status. These tables have an ID that is a uniqueidentifier. I'm trying to create a stored procedure that will allow me to pass the table name, name of the ID column, and the value I want.
I've tried this:
ALTER PROCEDURE [dbo].[GET_TABLE_DATA_BY_ID]
#table nvarchar(50),
#tableid uniqueidentifier,
#value uniqueidentifier
AS
BEGIN
SET NOCOUNT ON;
DECKALE #cmd AS nvarchar(max)
SET #cmd = N'select * ' +
'from ' + #table +
'where ' + cast(#tableid as nvarchar) + '= #value'
EXEC sp_executesql #cmd
END
The procedure adds fine. But when I execute the procedure I get this error:
Msg 8114, Level 16, State 5, Procedure GET_TABLE_DATA_BY_ID, Line 0
Error converting data type nvarchar to uniqueidentifier.
Is this even possible? Otherwise I would have to write many different procedures, not to mention the many different C# functions.
When I right click on the procedure and enter the values to test it creates this:
DECLARE #return_value int
EXEC #return_value = [dbo].[GET_TABLE_DATA_BY_ID]
#table = N'UserProfile',
#tableid = UserId,
#value = 'FB743B78-5B90-4A52-8177-6D516884700B'
SELECT 'Return Value' = #return_value
GO
I get the error :
Error converting data type nvarchar to uniqueidentifier.
I redid the procedure per suggestion to this:
DECLARE #cmd NVARCHAR(MAX) =
N'SELECT *
FROM #table
WHERE tableid = #value',
#param_list NVARCHAR(MAX) =
N'#table NVARCHAR(50),
#tableid UNIQUEIDENTIFIER';
EXEC [dbo].[sp_executesql]
#cmd
,#param_list
,#table
,#tableid;
When I do this in a new query window, I get the right data:
select * from UserProfile where UserId = 'FB743B78-5B90-4A52-8177-6D516884700B'
But it doesn't work when I execute the proc with those values -
Msg 105, Level 15, State 1, Line 4
Unclosed quotation mark after the character string '#value'.
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near '#value'.
Use explicit parameters:
SqlFiddleDemo
DECLARE
#tablename NVARCHAR(100) = 'tab1',
#tableid NVARCHAR(100) = 'a',
#value UNIQUEIDENTIFIER = '2FD22D07-E128-4133-ABA9-9B75215CB465'
DECLARE
#cmd NVARCHAR(MAX) =
N'SELECT *
FROM ' + QUOTENAME(#tablename) +
'WHERE ' + QUOTENAME(#tableid) + ' = #value'
EXEC [dbo].[sp_executesql]
#cmd
, N'#value UNIQUEIDENTIFIER'
, #value
I am having a problem with executing one SQL query, Below is my stored procedure
Query
ALTER PROCEDURE ProcName
(
#iID VARCHAR(50),
#AccountID INT
)
AS
SET NOCOUNT ON
DECLARE #Sql VARCHAR(MAX)
SET #Sql = 'DELETE FROM ReferringPhysician WHERE iID IN(' + #iID + ') AND AccountID = '+ #AccountID + ''
EXEC (#Sql)
I am trying to execute this query but it gives me error because i am using exec(), Here in my where condition i am dealing with the string, and in another condition i am dealing with the int, so in second condition i am getting casting error! how can i get through this?
Any help is greatly Appreciated!
Thanks
Your query is susceptible to SQL injection.
One way to avoid the data type problem you are having is to pass proper data types where you can and not use EXEC() (more details here):
DECLARE #sql NVARCHAR(MAX) = N'DELETE dbo.referringPhysician
WHERE iID IN (' + #iID + ') AND AccountID = #AccountID;';
EXEC sp_executesql #sql, N'#AccountID INT', #AccountID;
You can completely protect this from SQL injection by using table-valued parameters and passing in a DataTable or other collection with proper types instead of a comma-delimited string. e.g.:
CREATE TYPE dbo.iIDs TABLE(iID INT PRIMARY KEY);
Now your stored procedure can avoid dynamic SQL altogether:
ALTER PROCEDURE dbo.ProcName -- always use schema prefix!
#iIDs dbo.iIDs READONLY,
#AccountID INT
AS
BEGIN
SET NOCOUNT ON;
DELETE r
FROM dbo.ReferringPhysician AS r
INNER JOIN #iIDs AS i
ON r.iID = i.iID
WHERE r.AccountID = #AccountID;
END
GO
Try this:
ALTER PROCEDURE ProcName
(
#iID VARCHAR(50),
#AccountID INT
)
AS
SET NOCOUNT ON
DECLARE #Sql VARCHAR(MAX)
SET #Sql = 'DELETE FROM ReferringPhysician WHERE iID IN(' + CAST(#iID AS VARCHAR) + ') AND AccountID = '+ CAST(#AccountID AS VARCHAR) + ''
EXEC (#Sql)
In this stored procedure I want to get list of all the tables of a specific database when I give the database name as input.
For example when I call sp_list(master) it shows me the tables of the master database.
How can do this using sp_msforeachtable?
I found this code
sp_msforeachtable ' select ''?'' as ''Table'', count(*) as ''Rows'' from ? '
but cannot give database name in it as input
From this webpage:
declare #query as nvarchar(max)
declare #dbname as nvarchar(max)
SET #query=''
SET #dbname ='TST'
SET #query =#query + #dbname + '..sp_msforeachtable '' select ''''?'''' as ''''Table'''', count(*) as ''''Rows'''' from ? '''
EXEC sp_executesql #query
I have A stored procedure written
DECLARE #AreaID AS INT
DECLARE #DayPrior AS INT
DECLARE #TableName AS VARCHAR(50)
DECLARE #StoreQuery AS NVARCHAR(MAX)
DECLARE #SQL_ExtractDlSql AS NVARCHAR(MAX)
DECLARE #ParameterDefinition AS NVARCHAR(2000)
SET #AreaID = 1
SET #DayPrior = 1
SET #TableName = 'Tbl_Lube'
SET #SQL_ExtractDlSql = 'SELECT Download_SQL From
HDDDataPackage.dbo.tbl_HDD_DataDownloadSetting
Where AreaId=#AreaID AND TableName=#TableName'
SET #ParameterDefinition = '#AreaID INT,#DayPrior INT,#TableName VARCHAR(50)'
EXECUTE sp_executesql #SQL_ExtractDlSql,
#ParameterDefinition,
#AreaID,
#DayPrior,
#TableName
PRINT #SQL_ExtractDlSql
I above Stored procedure, I get What I wanted on print, but instead of doing that, I wanted the selected data stores as a variable.
Then what I done is I declared a variable #StoreSql and made some modified into the SQL statement show below:
Variable Declaration:
DECLARE #StoreSql AS NVARCHAR(MAX)
Modified the Code:
SET #SQL_ExtractDlSql = 'SELECT #StoreSql = Download_SQL From
HDDDataPackage.dbo.tbl_HDD_DataDownloadSetting
Where AreaId=#AreaID AND TableName=#TableName'
I executed the code, I get error Must declare the scalar variable "#StoreSql".
I have totally no idea how to deal with this.Any one can help.Beside,I am new to sqlserver,new to stored procedures.
Please don't hesitate to point out my any mistake,any..such as logic or etc. I learn from mistake.
Regards
LiangCk
The dynamic SQL string cannot reference variables from the outer scope. You need to declare it as an output parameter
SET #ParameterDefinition = '#AreaID INT,
#DayPrior INT,
#TableName VARCHAR(50),
#StoreSql NVARCHAR(MAX) OUTPUT'
EXECUTE sp_executesql #SQL_ExtractDlSql,
#ParameterDefinition,
#AreaID,
#DayPrior,
#TableName,
#StoreSql OUTPUT