I have a database in which contain product details The product code, name etc are the columns, I have the product images in the system in a folder I need to add the images directly to the database according to the proper rows regarding the product code, The product code and images are sam, the product code is like 110-1,110-2 etc, and image names are 110-1jpg,110-2jpg etc I have a program but its not updating all the rows pls help
DECLARE #CODE varchar
DECLARE image_cursor CURSOR FOR
SELECT CODE FROM MyMast WHERE img IS NULL
OPEN image_cursor;
FETCH NEXT FROM image_cursor
INTO #CODE;
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #sql VARCHAR(MAX)
DECLARE #imagePath VARCHAR(255)
SET #imagePath = 'D:\images\' + RTRIM(LTRIM(#CODE)) + '.jpg'
SET #sql = 'UPDATE Mymast'
SET #sql = #sql + 'SET img = (SELECT BulkColumn FROM OPENROWSET( BULK ''' + #imagePath + ''', Single_Blob) AS Picture), SET PictureFileName = ' + #imagepath
SET #sql = #sql + 'WHERE CODE = ''' + #CODE + ''';'
BEGIN TRY
EXECUTE sp_executesql #sql
END TRY
BEGIN CATCH
END CATCH
FETCH NEXT FROM image_cursor
INTO #CODE;
END
CLOSE image_cursor;
DEALLOCATE image_cursor;
SELECT CODE, img FROM MyMast WHERE img IS NOT NULL
DECLARE #CODE int
DECLARE image_cursor CURSOR FOR
SELECT CODE FROM MyMast WHERE img IS NULL
OPEN image_cursor;
FETCH NEXT FROM image_cursor
INTO #CODE;
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #sql NVARCHAR(MAX)
DECLARE #imagePath NVARCHAR(255)
SET #imagePath = 'D:\images\'+ RTRIM(LTRIM('12')) + '.jpg'
SET #sql = 'UPDATE MyMast '
SET #sql = #sql + 'SET img = (SELECT BulkColumn FROM OPENROWSET( BULK ''' + #imagePath + ''', Single_Blob) AS img) '
SET #sql = #sql + 'WHERE CODE = ' + STR(#CODE)
BEGIN TRY
EXECUTE sp_executesql #sql
END TRY
BEGIN CATCH
END CATCH
FETCH NEXT FROM image_cursor
INTO #CODE;
END
CLOSE image_cursor;
DEALLOCATE image_cursor;
SELECT CODE, img FROM MyMast WHERE img IS NOT NULL
I have tried this code, but it shows error in convertion of nvarchar to float, code is in the format 110-1
Related
I am trying to execute this query:
declare #tablename varchar(50)
set #tablename = 'test'
select * from #tablename
This produces the following error:
Msg 1087, Level 16, State 1, Line 5
Must declare the table variable "#tablename".
What's the right way to have the table name populated dynamically?
For static queries, like the one in your question, table names and column names need to be static.
For dynamic queries, you should generate the full SQL dynamically, and use sp_executesql to execute it.
Here is an example of a script used to compare data between the same tables of different databases:
Static query:
SELECT * FROM [DB_ONE].[dbo].[ACTY]
EXCEPT
SELECT * FROM [DB_TWO].[dbo].[ACTY]
Since I want to easily change the name of table and schema, I have created this dynamic query:
declare #schema sysname;
declare #table sysname;
declare #query nvarchar(max);
set #schema = 'dbo'
set #table = 'ACTY'
set #query = '
SELECT * FROM [DB_ONE].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table) + '
EXCEPT
SELECT * FROM [DB_TWO].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table);
EXEC sp_executesql #query
Since dynamic queries have many details that need to be considered and they are hard to maintain, I recommend that you read: The curse and blessings of dynamic SQL
Change your last statement to this:
EXEC('SELECT * FROM ' + #tablename)
This is how I do mine in a stored procedure. The first block will declare the variable, and set the table name based on the current year and month name, in this case TEST_2012OCTOBER. I then check if it exists in the database already, and remove if it does. Then the next block will use a SELECT INTO statement to create the table and populate it with records from another table with parameters.
--DECLARE TABLE NAME VARIABLE DYNAMICALLY
DECLARE #table_name varchar(max)
SET #table_name =
(SELECT 'TEST_'
+ DATENAME(YEAR,GETDATE())
+ UPPER(DATENAME(MONTH,GETDATE())) )
--DROP THE TABLE IF IT ALREADY EXISTS
IF EXISTS(SELECT name
FROM sysobjects
WHERE name = #table_name AND xtype = 'U')
BEGIN
EXEC('drop table ' + #table_name)
END
--CREATES TABLE FROM DYNAMIC VARIABLE AND INSERTS ROWS FROM ANOTHER TABLE
EXEC('SELECT * INTO ' + #table_name + ' FROM dbo.MASTER WHERE STATUS_CD = ''A''')
Use:
CREATE PROCEDURE [dbo].[GetByName]
#TableName NVARCHAR(100)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #sSQL nvarchar(500);
SELECT #sSQL = N'SELECT * FROM' + QUOTENAME(#TableName);
EXEC sp_executesql #sSQL
END
You can't use a table name for a variable. You'd have to do this instead:
DECLARE #sqlCommand varchar(1000)
SET #sqlCommand = 'SELECT * from yourtable'
EXEC (#sqlCommand)
You'll need to generate the SQL content dynamically:
declare #tablename varchar(50)
set #tablename = 'test'
declare #sql varchar(500)
set #sql = 'select * from ' + #tablename
exec (#sql)
Use sp_executesql to execute any SQL, e.g.
DECLARE #tbl sysname,
#sql nvarchar(4000),
#params nvarchar(4000),
#count int
DECLARE tblcur CURSOR STATIC LOCAL FOR
SELECT object_name(id) FROM syscolumns WHERE name = 'LastUpdated'
ORDER BY 1
OPEN tblcur
WHILE 1 = 1
BEGIN
FETCH tblcur INTO #tbl
IF ##fetch_status <> 0
BREAK
SELECT #sql =
N' SELECT #cnt = COUNT(*) FROM dbo.' + quotename(#tbl) +
N' WHERE LastUpdated BETWEEN #fromdate AND ' +
N' coalesce(#todate, ''99991231'')'
SELECT #params = N'#fromdate datetime, ' +
N'#todate datetime = NULL, ' +
N'#cnt int OUTPUT'
EXEC sp_executesql #sql, #params, '20060101', #cnt = #count OUTPUT
PRINT #tbl + ': ' + convert(varchar(10), #count) + ' modified rows.'
END
DEALLOCATE tblcur
You need to use the SQL Server dynamic SQL:
DECLARE #table NVARCHAR(128),
#sql NVARCHAR(MAX);
SET #table = N'tableName';
SET #sql = N'SELECT * FROM ' + #table;
Use EXEC to execute any SQL:
EXEC (#sql)
Use EXEC sp_executesql to execute any SQL:
EXEC sp_executesql #sql;
Use EXECUTE sp_executesql to execute any SQL:
EXECUTE sp_executesql #sql
Declare #tablename varchar(50)
set #tablename = 'Your table Name'
EXEC('select * from ' + #tablename)
Also, you can use this...
DECLARE #SeqID varchar(150);
DECLARE #TableName varchar(150);
SET #TableName = (Select TableName from Table);
SET #SeqID = 'SELECT NEXT VALUE FOR ' + #TableName + '_Data'
exec (#SeqID)
Declare #fs_e int, #C_Tables CURSOR, #Table varchar(50)
SET #C_Tables = CURSOR FOR
select name from sysobjects where OBJECTPROPERTY(id, N'IsUserTable') = 1 AND name like 'TR_%'
OPEN #C_Tables
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
WHILE ( #fs_e <> -1)
BEGIN
exec('Select * from ' + #Table)
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
END
I have one question on the TSQL Linked Server Query. Linked Server is GIS enforced so we pass the coordinates to that server which it returns the data from the Linked Server. Please find the below-working query.
DECLARE #input varchar(max), #sql varchar(max);
SET #input = N'((-119.470830216356 46.2642458295079,-119.470722927989 46.2642050348762,-119.470076515615 46.2647075484513,-119.470240130371 46.2647075484512,-119.470830216356 46.2642458295079))'
BEGIN
SELECT #sql = 'select * from openquery([LinkedServerName],''DECLARE #b geometry;
SET #b = geometry::STGeomFromText(''''POLYGON '+ #input + ' '''', 4326);
SET #b = #b.MakeValid();
SELECT * from [Database].[Table] AS b
where b.Shape.STIntersects(#b.STCentroid()) = 1'')'
END
EXEC(#sql)
But the issue is sometimes we have to pass more than 8000 characters to the input parameter #input since it is varchar(max) and EXEC command both have an 8000 character limitation. So we are trying to get rid of Dynamic SQL so that we can pass the input using 2 input variables (We have implemented splitting the input into subsets each of 8000 characters in our C# code and sending them as 2 different inputs to the SQL Query). We have tried the below query in the Actual Server (Linked Server) which is working fine.
DECLARE #b geometry
SET #input = N'((-119.470830216356 46.2642458295079,-119.470722927989 46.2642050348762,'
SET #input2 = N'-119.470076515615 46.2647075484513,-119.470240130371 46.2647075484512,-119.470830216356 46.2642458295079))'
SELECT #b = geometry::STGeomFromText('POLYGON ' + #input + #input2 + '', 4326)
SELECT #b = #b.MakeValid()
SELECT * FROM [Database].[TableName] AS b
WHERE b.Shape.STIntersects(#b.STCentroid()) = 1
We tried below SQL Linked query in our local server but it is throwing below error
DECLARE #input varchar(max), #input2 varchar(max);
SET #input = N'((-119.470830216356 46.2642458295079,-119.470722927989 46.2642050348762,'
SET #input2 = N'-119.470076515615 46.2647075484513,-119.470240130371 46.2647075484512,-119.470830216356 46.2642458295079))'
SELECT * FROM OPENQUERY([LinkedServerName],
'DECLARE #b geometry;
SELECT #b = geometry::STGeomFromText(''''POLYGON ' + #input + #input2 + '' ', 4326);
SELECT #b = #b.MakeValid();
SELECT * FROM [DatabaseName].[TableName] AS b
where b.Shape.STIntersects(#b.STCentroid()) = 1') AS AD
In the above query, an issue has been highlighted in the attached image.
Help is really appreciated.
I want to use the return value from one stored procedure to another stored procedure. I was searching on the internet and try several solutions, but all of them are not working, I don't know what the mistake I make.
The stored procedure that I want to use its return value is:
CREATE PROCEDURE dbo.pro_ForeignKeyCheck
(#tableName VARCHAR(100),
#columnName VARCHAR(100),
#idValue INT)
AS BEGIN
SET NOCOUNT ON
DECLARE fksCursor CURSOR FAST_FORWARD FOR
SELECT
tc.table_name, ccu.column_name
FROM
information_schema.table_constraints tc
JOIN
information_schema.constraint_column_usage ccu ON tc.constraint_name = ccu.constraint_name
JOIN
information_schema.referential_constraints rc ON tc.constraint_name = rc.constraint_name
JOIN
information_schema.table_constraints tc2 ON rc.unique_constraint_name = tc2.constraint_name
JOIN
information_schema.constraint_column_usage ccu2 ON tc2.constraint_name = ccu2.constraint_name
WHERE
tc.constraint_type = 'Foreign Key'
AND tc2.table_name = #tableName
AND ccu2.column_name = #columnName
ORDER BY
tc.table_name
DECLARE #fkTableName VARCHAR(100),
#fkColumnName VARCHAR(100),
#fkFound BIT,
#params NVARCHAR(100),
#sql NVARCHAR(500)
OPEN fksCursor
FETCH NEXT FROM fksCursor INTO #fkTableName, #fkColumnName
SET #fkFound = 0
SET #params = N'#fkFound BIT OUTPUT'
WHILE ##fetch_status = 0 AND COALESCE(#fkFound, 0) <> 1
BEGIN
SELECT #sql = 'set #fkFound = (select top 1 1 from [' + #fkTableName + '] where [' + #fkColumnName + '] = ' + cast(#idValue as varchar(10)) + ')'
PRINT #sql
EXEC sp_executesql #sql, #params, #fkFound OUTPUT
FETCH NEXT FROM fksCursor INTO #fkTableName, #fkColumnName
END
CLOSE fksCursor
DEALLOCATE fksCursor
SELECT COALESCE(#fkFound, 0)
RETURN 0
END
and this use to check if the primary key value used in all child tables, we call it like this
EXECUTE pro_ForeignKeyCheck 'tablename','columnName', 1
or
EXECUTE pro_ForeignKeyCheck #tablename = 'tablename', #columnName = 'columnName', #idValue = 1
and it will work, but I cannot use the return value in other stored procedure
CREATE PROCEDURE [dbo].[pro_Delete_acount]
#UserID int,
#Action NVARCHAR(10)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #count int , #ErrNo int , #ErrMsg varchar(2000), #exit int
set #exit=0
if #Action ='ADMIN'
begin
/*---------Call Store Procedure pro_ForeignKeyCheck to check if there is value are exit in child table*/
--EXEC #exit = pro_ForeignKeyCheck1 #tablename='tb_M_admin',#columnName='admin_id',#idValue= #UserID
--select #exit
--EXEC #exit = pro_ForeignKeyCheck #tablename='tb_M_admin',#columnName='admin_id',#idValue= 1
EXEC #exit = pro_ForeignKeyCheck 'tb_M_admin','admin_id', 0
--select #exit
select -2[Ret_Status],#exit[ErrNo],0[ErrMsg] -- test
end
end
Could anyone help me with that?
Thanks all
Add
#Status int OUTPUT
in the pro_ForeignKeyCheck so it starts with
CREATE PROCEDURE dbo.pro_ForeignKeyCheck1
#tableName VARCHAR(100),
#columnName VARCHAR(100),
#idValue int,
#Status int OUTPUT
and at the end of it did as follow
--select coalesce(#fkFound,0)
select #Status = coalesce(#fkFound,0)
--return 0
stop the last to line and add new one
In the other stored procedure, call it as follows
EXEC pro_ForeignKeyCheck1 'tb_M_admin','admin_id', 0 ,#exit output
select #exit
and now the return value will be used.
Thanks to all
EXEC #exit = pro_ForeignKeyCheck 'tb_M_admin','admin_id', 0
---
select coalesce(#fkFound,0)
return 0 --< this will be assigned to #exit
replace this code with
return IsNull(#fkFound, 0)
You may leave select for other purposes but it cannot affect RETURN value. So you may remove it either.
This is oversimplified example of call of one SP from another. I hope it will give you some ideas.
create procedure dbo.first_proc
#bd datetime,
#d int output
as
select #d= DATEDIFF(day,#bd,getdate())
go
create procedure dbo.sec_proc
#birthday datetime
as
declare #days int
exec dbo.first_proc #birthday, #days output
select 'you live '+cast(#days as varchar) + ' days' result
go
exec dbo.sec_proc '1959-09-17'
I want to create a new table with existing table, where the table names should to pass from input parameters.
I am trying the following code.
DECLARE #oldTableName nvarchar(50)
DECLARE #newStagingTableName nvarchar(50)
SET #oldTableName='OldTableName'
SET #newStagingTableName ='NewTableName';
SELECT * INTO #newStagingTableName FROM #oldTableName WHERE 1 = 0;
The SQL server is giving error while parsing this query.
Could you please try below dynamic SQL query?
DECLARE #oldTableName nvarchar(50)
DECLARE #newStagingTableName nvarchar(50)
SET #oldTableName='OldTableName'
SET #newStagingTableName ='NewTableName'
DECLARE #sqlquery nvarchar(100) = 'SELECT * INTO ' + #newStagingTableName + ' FROM ' + #oldTableName
exec(#sqlquery)
On the line
SELECT * INTO #newStagingTableNameFROM #oldTableName WHERE 1 = 0;
you do not have a space between #newStagingTableName and FROM
also check does the table NewTableName exist ? and if so you cannot just access it directly via a parameter - you would need to use dynamic SQL - perhaps this can help
Try with this
DECLARE #oldTableName NVARCHAR(50)
DECLARE #newStagingTableName NVARCHAR(50),
#sql NVARCHAR(100)=''
SET #oldTableName=''
SET #newStagingTableName ='';
SET #sql='select * INTO ' + #newStagingTableName
+ ' FROM ' + #oldTableName + ' WHERE 1 = 0;'
EXEC sp_executesql
#sql
this should work . . .
DECLARE #oldTableName nvarchar(50)
DECLARE #newStagingTableName nvarchar(50)
declare #sql nvarchar(max);
SET #oldTableName='oldTableName'
SET #newStagingTableName ='newStagingTableName ';
SET #sql='SELECT * INTO ' + #newStagingTableName + ' FROM ' + #oldTableName + ' WHERE 1 = 0;'
exec sp_executesql #sql
EDIT: Sorry I didnt see that other guys answered it
I have a stored procedure which gives different result in only a specific case.
When I call it from SQL Server Management Studio 2008 R2, it gives me 0 as output.
When I call it from C# class file. It gives me 1 as output.
I am using edmx file, and it is updated for sure.
The call is something like below from SSMS [SQL Server Management Studio]
exec proc_GetPrimaryKeyUsageCount 62, 'tblFormula'
This gives output as 0
The same stored procedure is called from C# file is like below
_db.GetPrimaryKeyUsageCount(62, "tblFormula");
This gives output as 1
The stored procedure is
CREATE PROCEDURE proc_GetPrimaryKeyUsageCount (
#PrimaryKeyColumnId INT
,#PrimaryKeyTable NVARCHAR(max)
--,#Response INT OUTPUT
)
AS
BEGIN
DECLARE #counter INT
DECLARE #sqlCommand NVARCHAR(max)
DECLARE #ForeignKey TABLE (
child_table VARCHAR(max)
,child_fk_column VARCHAR(max)
)
DECLARE #child_table VARCHAR(max)
DECLARE #child_fk_column VARCHAR(max)
SET #counter = 0
INSERT INTO #ForeignKey
SELECT child_table = c.TABLE_NAME
,child_fk_column = c.COLUMN_NAME
FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE p
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS pc ON pc.UNIQUE_CONSTRAINT_SCHEMA = p.CONSTRAINT_SCHEMA
AND pc.UNIQUE_CONSTRAINT_NAME = p.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE c ON c.CONSTRAINT_SCHEMA = pc.CONSTRAINT_SCHEMA
AND c.CONSTRAINT_NAME = pc.CONSTRAINT_NAME
WHERE EXISTS (
SELECT 1
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'IsDeleted'
AND TABLE_SCHEMA = p.TABLE_SCHEMA
AND TABLE_NAME = p.TABLE_NAME
AND p.TABLE_NAME = #PrimaryKeyTable
)
DECLARE db_cursor CURSOR
FOR
SELECT child_table
,child_fk_column
FROM #ForeignKey
OPEN db_cursor
FETCH NEXT
FROM db_cursor
INTO #child_table
,#child_fk_column
WHILE ##FETCH_STATUS = 0
BEGIN
PRINT 'select count(*) from ' + CAST(#child_table AS VARCHAR) + ' where ' + CAST(#child_fk_column AS VARCHAR) + ' = ' + CAST(#PrimaryKeyColumnId AS VARCHAR)
SET #sqlCommand = 'select #cnt=count(*) from ' + CAST(#child_table AS VARCHAR) + ' where ' + CAST(#child_fk_column AS VARCHAR) + ' = ' + CAST(#PrimaryKeyColumnId AS VARCHAR)
EXEC sp_executesql #sqlCommand
,N'#cnt int OUTPUT'
,#cnt = #counter OUTPUT
IF #counter > 0
BREAK
FETCH NEXT
FROM db_cursor
INTO #child_table
,#child_fk_column
END
SELECT #counter AS [PrimaryKeyUsageCount]
END
1st argument is Id of the primary key and 2nd argument is the name of the table having that primary key.
The Procedure returns the count of the usage of primary key in other tables in same database. If it finds even 1 occurrence, it will return that count otherwise 0.
If anything extra is needed please do let me know.
There are couple of mistakes, which could cause the problem.
The INSERT should be like that:
INSERT INTO #ForeignKey
SELECT c.TABLE_NAME,c.COLUMN_NAME
FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE p
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS pc ON pc.UNIQUE_CONSTRAINT_SCHEMA = p.CONSTRAINT_SCHEMA
AND pc.UNIQUE_CONSTRAINT_NAME = p.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE c ON c.CONSTRAINT_SCHEMA = pc.CONSTRAINT_SCHEMA
AND c.CONSTRAINT_NAME = pc.CONSTRAINT_NAME
WHERE EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS AS isc
WHERE isc.COLUMN_NAME = 'IsDeleted'
AND isc.TABLE_SCHEMA = p.TABLE_SCHEMA
AND isc.TABLE_NAME = p.TABLE_NAME
AND p.TABLE_NAME = #PrimaryKeyTable
)
After cursor loop shoud be:
CLOSE db_cursor
DEALLOCATE db_cursor